动态查询从表中打印出结果集

时间:2015-09-09 14:08:06

标签: sql-server-2012 dynamic-sql

我想打印出动态查询结果,以便我可以用作某些任务的脚本。这是我卡住的情况,我无法打印出结果,因为它只返回最后一个值,因为OUTPUT参数限制 有没有办法打印所有3 INSERT语句。

    --IF OBJECT_ID ('tempdb.dbo.#temp') IS NOT NULL


    CREATE TABLE #temp (Command varchar(8000))
    INSERT INTO #temp 
    SELECT 'INSERT INTO Test1(column1,column2)values(1,2)'
    UNION ALL
    SELECT 'INSERT INTO Test2(column1,column2)values(1,2)'
    UNION ALL
    SELECT 'INSERT INTO Test3(column1,column2)values(1,2)'

    DECLARE @Column_string varchar(max)
    DECLARE @Column_string_Out varchar(max)
    DECLARE @SQL NVARCHAR(MAX)
    SELECT @SQL = 'SELECT @Column_string = Command FROM #temp'

    --PRINT(@SQL)
    EXECUTE sp_executesql @SQL,N'@Column_string varchar(max) OUTPUT',@Column_string = @Column_string_Out Output
    --EXEC sys.sp_executesql @SQL
    PRINT(@Column_string_Out)
DROP TABLE #temp

1 个答案:

答案 0 :(得分:0)

使用光标:

CREATE TABLE #temp (Command varchar(8000))
INSERT INTO #temp 
SELECT 'INSERT INTO Test1(column1,column2)values(1,2)'
UNION ALL
SELECT 'INSERT INTO Test2(column1,column2)values(1,2)'
UNION ALL
SELECT 'INSERT INTO Test3(column1,column2)values(1,2)'

DECLARE @Column_string varchar(max)
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = 'Declare  cur CURSOR FOR SELECT Command FROM #temp'
exec sp_executesql @SQL

open cur
FETCH NEXT FROM cur
INTO @Column_string

WHILE @@FETCH_STATUS = 0
BEGIN
Print @Column_string

FETCH NEXT FROM cur
INTO @Column_string

END
CLOSE cur
DEALLOCATE cur    
DROP TABLE #temp

<强>输出:

(3 row(s) affected)
INSERT INTO Test1(column1,column2)values(1,2)
INSERT INTO Test2(column1,column2)values(1,2)
INSERT INTO Test3(column1,column2)values(1,2)