Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use enums in TSQL without hard coding magic number all over my SQL scripts/procs?

Tags:

c#

enums

tsql

We have enums in our C# code:

public enum JobStatus
{        
  Ready = 0,      
  Running = 1,        
  Cancelling = 2,
}

These values are also stored in database fields, and we have lots of TSQL (mostly stored procs, as well as some batches and SSIS) that also processes the data:

SELECT TOP 1 @JobSID = JobSID
FROM Job 
WHERE Status = 0 /* JobStatus.Ready */
ORDER BY SubmitDate ASC

CREATE TABLE ImportCrossEffect(
    /* lots deleted */      
    Source tinyint 
      DEFAULT 1 NOT NULL -- 0: Unknown (default), 1:Imported, 2:Keyed
) 

How do I avoid hard coding the “magic numbers” in the TSQL?
How do I remove the risk of the enumerations not matching on the C# and TSQL sides?

(I have included the C# tag, as I would like solution that “single sourced” the definitions of the enums on both the C# and TSQL sides)


Updates:

We don't have tables in the database with the Enum names in them, the values are just stored in tiny int columns.

I was hoping for something like a SQL pre-processor that would "expand" all the enum to there "magic value".

like image 878
Ian Ringrose Avatar asked Dec 14 '10 16:12

Ian Ringrose


People also ask

How do I create an ENUM in SQL?

In MySQL one can create an enum as such: USE WorldofWarcraft; CREATE TABLE [users] ( ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY, username varchar(255), password varchar(255), mail varchar (255), rank ENUM ('Fresh meat', 'Intern','Janitor','Lieutenant','Supreme being')DEFAULT 'Fresh meat', );

How do you insert an ENUM?

To insert data into an ENUM column, you use the enumeration values in the predefined list. For example, the following statement inserts a new row into the tickets table. In this example, instead of using the Low enumeration value, we used value 1. Since Low is mapped to 1, it is acceptable.

How can I get ENUM possible values in a MySQL database?

$syntax = mysql_query("SELECT COLUMN_TYPY FROM information_schema. `COLUMNS` WHERE TABLE_NAME = '$table' AND COLUMN_NAME ='$colm'"); if (! mysql_error()){ //Get a array possible values from table and colm.


1 Answers

You can always pass the value from the enumeration into the stored proc/command that you are trying to execute. This way, you never have to worry about the enumerations in the database.

If you want to store the enumerations in the database, then I suggest you create a view (possibly titled with your enumeration), like so:

create view JobStatus
    select 0 as Ready, 1 as Running, 2 as Cancelling

You can then access/join on the view if you need it to.

Note, the query optimizer treats any reference to the above as a constant scan/scalar operation, not a table scan, so you aren't incurring the reads that would occur if you were accessing an actual table.

like image 126
casperOne Avatar answered Sep 18 '22 19:09

casperOne