I have a table in SQL Server of key-value pairs along with a field containing the T-SQL data type and other fields to indicate whether a particular field is mandatory, unique, etc. I have written a stored procedure to output a normalised table of data, using the data type field to define the type of each field. This works well. However, before running it, I run another procedure to check for potential errors. One obvious check is: does any data violate the specified type?
I would like to write something like this:
SELECT [key], [value], [type]
FROM [source_table]
WHERE TRY_CONVERT([type], [value]) Is Null AND [value] Is Not Null
which would return the records where the conversion fails (with some exceptions, e.g. int to date). However, this does not work because the first argument of TRY_CONVERT must be a keyword.
They only solution I have found is to produce a block of SQL dynamically which runs once for each datatype to be checked. However, this is irritatingly long winded! I wonder if anyone has found a more succinct way? This must be a common problem.