Using Variable for Column name
It is very straight forward to use direct column names in T-SQL statements. But what if column names are dynamically supplied to T-SQL code? Can we use variables instead of column names in our query? Yes we can.
When I first came across this problem, it took me hell lot of time to find a simple solution to it. What we need to do is build the SQL statement in a string variable with all the variable names in it. And then pass it to the EXEC command for execution.
Example:
– Customer Table contains column Acc1, Acc2, Acc3 … Acc16
– We need to display Acc[???] column for given CustID – ??? -> is value supplied dynamically
DECLARE @sqlQuery VARCHAR(1000)
DECLARE @custID VARCHAR(10)
DECLARE @acc VARCHAR(5)
– here we are assigning ’5′ for demo.
SET @acc = ’5′
SET @acc = ‘Acc’+@acc
SET @custID=‘C308′
– Bulid the Query into a string variable
SET @sqlQuery =
(‘SELECT (‘+QUOTENAME(@acc)+‘) FROM Customer WITH (NOLOCK)
WHERE CustID=’+@CustID+‘ AND (‘+QUOTENAME(@acc)+‘) IS NOT NULL’)
– Pass the String to EXEC for execution
EXEC (@sqlquery)
Dynamic column names are generally used by user define stored procedures that takes the input which need to be passed to the SQL statement. Below is the simple USP which demonstrates the used of variable column name.
Eaxmple:
– Table StudentAttendance has columns day1, day2, day3 … and so on
– The USP displays only the column, as per number supplied.
ALTER PROCEDURE [dbo].[USP_studentExist]
(
@AcademicYearFrom INT,
@AcademicYearTo INT,
@month INT,
@day VARCHAR(5),
@StudentID VARCHAR(11)
)
AS
BEGIN
BEGIN TRY
DECLARE @query VARCHAR (1000)
DECLARE @m VARCHAR(50),
@ayf VARCHAR(50),
@ayt VARCHAR(50)
– Converting INT value to VARCHAR values
SELECT @m=@month, @ayf=@AcademicYearFrom, @ayt=@AcademicYearTo
– Bulid the Query into a string variable
SET @query = (‘SELECT day’+@day+‘ FROM dbo.StudentAttendance
WHERE studentid = ”’+@StudentID+”’
AND month=’+@m+‘
AND AcademicYearFrom=’+@ayf+’
AND AcademicYearTO=’+@ayt+”)
EXEC (@query)
END TRY
BEGIN CATCH
PRINT @@ERROR
END CATCH
END
Be very careful with the use of use of single quote (‘) while building a query string. A silly error while using it may take lot of time to debug.
Good Luck!
Posted by ckoryomro on November 15, 2011 at 8:47 pm
Gracias!!!!!