I have a sql table with a structure like this:
Each column is a hour of day (I can’t change the structure of table)
If I want to get the value of 13:00pm I have to write a query like this:
SELECT TAB.[13] FROM TABLE AS TAB
I want to know if is possible make something like this:
SELECT TAB.[TRY_CONVERT(varchar,DATEPART(HOUR, dateadd(hour,-7,GETUTCDATE())))] FROM TABLE AS TAB
Advertisement
Answer
You need to use dynamic TSQL for the job. You can encapsulate the below script in a scalar function if you want to. I’m assuming the data type for all numbered columns is int.
DECLARE @tbl TABLE (OUTVALUE int); DELETE FROM @tbl; DECLARE @columnName nvarchar(128) = CAST(DATEPART(HOUR, dateadd(hour,-7,GETUTCDATE())) AS varchar(128)); IF LEN(@columnName) = 1 SET @columnName = '0' + @columnName; DECLARE @dynamicSql nvarchar(500) = 'SELECT TOP 1 TAB.[' + @columnName + '] FROM TABLE AS TAB;'; INSERT INTO @tbl EXEC sp_executesql @dynamicSql; SELECT OUTVALUE FROM @tbl;
As mentioned by Gordon Linoff this is a really bad table design. The table should really have 2 columns: one to indicate the hour of the day and the other the associated value.