Using dynamic SQL to specify a column name by adding a variable to simple sql query
sql 2005/ sql 2008
Declare @temp nvarchar(1000)
set @temp = 'ABC'
select col1,col2 from tableA
Along with sele开发者_高级运维ct query, how to add a variable to the select query ?
expected output :-
select col1,col2,@temp as [col3] from tableA
Where @temp specifies the name of a column in tableA.
If you are trying to specify the column name dynamically, you could take a look at executing dynamic sql. However, you should make sure to read about the dangers of this approach first:
http://www.sommarskog.se/dynamic_sql.html
From that page, there is a sample that shows dynamically specifying the table name -- you could change it so it dynamically specifies the column name instead:
CREATE PROCEDURE general_select @tblname nvarchar(128),
@key varchar(10),
@debug bit = 0 AS
DECLARE @sql nvarchar(4000)
SET @sql = 'SELECT col1, col2, col3
FROM dbo.' + quotename(@tblname) + '
WHERE keycol = @key'
IF @debug = 1 PRINT @sql
EXEC sp_executesql @sql, N'@key varchar(10)', @key = @key
So for example if you had a table 'MyTable' with columns named 'x', 'y', and 'z', it might look like:
DECLARE @columnName nvarchar(128)
DECLARE @sql nvarchar(4000)
set @columnName = 'z'
SET @sql = 'SELECT x, y, ' + @columnName + ' from MyTable'
EXEC sp_executesql @sql, N'@columnName varchar(128)', @columnName = @columnName
Something like this:
select col1,col2 from tableA WHERE col1 = @temp
Or this:
select col1,col2,@temp as col3 from tableA WHERE col1 = @temp
Or this:
select col1,col2,@temp as col3 from tableA
Or if @temp is a column name, then maybe you're looking for a dynamic query?
SET @temp = 'select col1,col2, ' + @temp + ' as col3 from tableA'
EXEC sp_executesql @temp
...
精彩评论