我构建了一个sql查询:
declare @query1 varchar(1000)
declare @results varchar(4000)
set @results = ''
WHILE (condition)
BEGIN
set @query1 = 'SELECT column FROM table'
set @results = @results + ", " + (select @query1)
END
print @results
所以,例如在2次迭代之后,我希望:
columnvalue, columnvalue
但是,在上面的代码中,@results代替了实际的sql查询。
答案 0 :(得分:0)
您永远不会执行query1,而是为其分配文本字符串SELECT COLUMN FROM table
。
您正在寻找的内容类似于SELECT @query1 = column from table
答案 1 :(得分:0)
声明@ query1 varchar(1000)
声明@results varchar(4000)
设置@results =''
IF OBJECT_ID('tempdb ..#ResultSet')IS NOT NULL
BEGIN
DROP TABLE #ResultSet;
结束
CREATE TABLE #ResultSet(mycolumn VARCHAR(1000))
WHILE(条件)
BEGIN
set @ query1 ='SELECT column FROM table'
INSERT INTO #ResultSet //临时表存储运行动态查询的结果
exec(@ query1)// Exec运行动态查询
SELECT @ query1 = mycolumn FROM #ResultSet
设置@results = @results +','+(选择@ query1)
END
print @results
drop table #ResultSet
希望这有帮助。
答案 2 :(得分:0)
行。这就是它的完成方式:
declare @query1 nvarchar(1000)
declare @results nvarchar(4000)
set @results = ''
declare @changesOUT nvarchar(1000)
set @query1 = 'SELECT @changes = column FROM table WHERE condition'
EXEC sp_executesql @query1, N'@changes varchar(4000) OUTPUT', @changes=@changesOUT OUTPUT
set @results = @results + (SELECT @changesOUT) + char(10)
print @results