我想在 SQL Server 存储过程中生成一个 select 语句。我在 SQL 参数中有列名。
我正在尝试使用所选列名以编程方式生成 select 语句,但似乎无法在存储过程中找到正确的语法。
CREATE PROCEDURE dbo.aProc
@testCondition int,
@colCount int,
@column_1 varchar(100) = null,
....
@column_40 varchar(100) null
AS
DECLARE @qry nvarchar(3000)
DECLARE @Iterator int
SET @testtype = 2
SET @Iterator = 0
SET @qry ='SELECT '
WHILE (@Iterator < @colCount-1)
BEGIN
SET @qry = @qry + ''+@column_''+CAST(@Iterator as varchar(2))+',''
Set @Iterator = @Iterator + 1
END
SET @qry = @qry + ''@column_+CAST(@colCount as varchar(2)) FROM aTable where aCol = @testCondition