SQL Server:静态SELECT与动态SELECT

时间:2014-04-02 22:29:46

标签: sql-server dynamic-programming

从tableA中选择0工作正常但它在动态sql中不起作用。我该如何解决这个问题?我必须在动态sql中包含@zerocol,同时选择列。

select top 10 col1,col2,col3,0 
from dbo.tableA

declare @table_name varchar(40)
declare @sqlstr VARCHAR(MAX)
declare @zerocol varchar(20)

set @table_name = 'dbo.tableA' 
set @zerocol = 0
SELECT @sqlStr = ' ; WITH Tableinfo1 AS (SELECT col1, 
col2, 
col3,
['+ @zerocol +'] 

FROM ' + @table_name + ' ) 

SELECT top 10 * FROM Tableinfo1'

EXEC (@sqlstr)

1 个答案:

答案 0 :(得分:0)

试试这个......

declare @table_name varchar(40)
declare @sqlstr VARCHAR(MAX)
declare @zerocol varchar(20)

set @table_name = 'dbo.tableA' 
set @zerocol = 0
SELECT @sqlStr = ' ; WITH Tableinfo1 AS (SELECT col1, 
col2, 
col3,
'+ @zerocol +' AS ZeroCol

FROM ' + @table_name + ' ) 

SELECT top 10 * FROM Tableinfo1'

EXEC (@sqlstr)