In code one can specify globally accessible constants/enums/etc once that can then be reused through out the application. This gives the ability to use meaningful names like 'Mazda' instead of numbers like '2'.
We would like to do the same with in our SQL Server stored procedures, but are not sure of the best way of implementing this.
E.g for the following tables (The proverbial car schema):
Car ManufacturerId
350Z 1
Hilux 2
Yaris 2
ManufacturerId Name
1 Nissan
2 Toyota
So instead of writing
SELECT * FROM Car WHERE ManufacturerId = 1 -- Nissan
We would like to write something like
SELECT * FROM Car WHERE ManufacturerId = @Nissan
One restriction we have is that we cannot rely on the Manufacturer.Name staying the same for the life of the App. We did think about having a column "Code" that never changes and the joins are looked up like this:
SELECT *
FROM Car c
INNER JOIN Manufacturer m ON c.ManufacturerId = m.ManufacturerId
WHERE m.Code = 'Nissan'
I'm a bit hesitant on this as it uses an extra join and string comparisons that can be misspelled.
What is the best way for this to be accomplished without having to declare the variables in every Stored Procedure?
SQL Server TRIM() Function The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string.
A magic number is a number in the code that seems arbitrary and has no context or meaning. This is considered an anti-pattern because it makes code difficult to understand and maintain. One of the most important aspects of code quality is how it conveys intention. Magic numbers hide intention so they should be avoided.
A magic table is stored in the temp DB. Therefore, whenever you use the magic tables in SQL Server with the query statement, tempdb will come in the picture.
We've done this a couple ways:
You don't need to store numbers in the database. There are DB admins out there who still love the idea of 'natural keys'. Instead of using an ID, they simply use a natural key that uniquely defines the manufacturer. Often this can lead to multiple primary keys. You might have to have a 'Mazda' 'Canada' as a unique identifier for manufacturer.
Personally, I dislike this method, and prefer to have a unique ID for every identifiable object stored in my tables. This means creating a new table which is a lookup. 2, 'Mazada'. Then you can create a view that pulls 'Mazda' in where there is 2 in the database, then run the query against the view. SELECT * from v_cars where maker = 'Mazda'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With