【问题标题】:SQL Server 2012 - using select * into along with dynamic SQLSQL Server 2012 - 使用 select * into 以及动态 SQL
【发布时间】:2018-05-22 07:15:00
【问题描述】:

您好,我有以下代码:

use TSQL2012; 
go

if OBJECT_ID('Sales.FreightTotals') is not null drop table 
Sales.FreightTotals
go 

declare @shipperid as nvarchar(max) ='';
declare @dsql as nvarchar(max);
select @shipperid += quotename(shipperid,'')+',' from sales.Orders group by 
shipperid;
set @shipperid = LEFT(@shipperid, LEN(@shipperid)-1)

print @shipperid; 

set @dsql='
select empid,'+@shipperid+' from
(select empid, shipperid, freight from Sales.Orders )as d  
pivot(sum(freight) for shipperid in('+@shipperid+')) as pvt
order by pvt.empid  
'

打印@dsql

--exec sp_executesql @dsql

select * into Sales.FreightTotals from @dsql;

我正在尝试将 select * into 与动态枢轴一起使用,如上所示。如果我使用

exec sp_executesql @dsql 

我得到以下结果我正在寻找的结果

empid       1                     2                     3
----------- --------------------- --------------------- --------------------
1           2194.73               3259.99               3381.92
2           2281.09               4350.20               2065.12
3           2491.74               4258.90               4134.10
4           3129.39               4926.73               3290.02
5           1218.27               1991.84               708.60
6           1049.83               1270.42               1460.22
7           1204.60               3155.18               2305.66
8           1889.27               3297.40               2301.21
9           726.41                1734.19               865.66

(9 rows affected)

但如果我这样做 select * into Sales.FreightTotals from @dsql;

我明白了:

Msg 1087, Level 16, State 1, Line 26
Must declare the table variable "@dsql".

关于为什么会这样的任何建议?

【问题讨论】:

  • 试试这个exec 'select * into Sales.FreightTotals from ('+ @dsql+') as tmp;

标签: sql-server tsql


【解决方案1】:

看起来您的局部变量“@dsql”是在您的存储过程中声明的。

因此,当您调用 sp 时,变量会在打印之前声明 - 'PRINT'

当您运行相同的打印行时,尚未声明变量,因此您收到错误消息。

【讨论】:

    【解决方案2】:

    试试下面的

    set @dsql='
    select empid,'+@shipperid+'
    into Sales.FreightTotals -- into is here
    from
    (select empid, shipperid, freight from Sales.Orders )as d  
    pivot(sum(freight) for shipperid in('+@shipperid+')) as pvt
    order by pvt.empid  
    '
    
    print @dsql -- print for check
    
    exec sp_executesql @dsql
    

    【讨论】:

      【解决方案3】:

      您不能在 from 子句中使用字符串代替表。

      如果您确实需要动态 SQL,您可以使用 insert ... exec 解决方法。

      插入 Sales.FreightTotals 执行 sp_executesql @dsql;

      【讨论】:

        【解决方案4】:

        尝试以下方法:

        exec ('select * into Sales.FreightTotals from ('+@dsql+')t;')
        

        谢谢。

        【讨论】:

          猜你喜欢
          • 2012-01-23
          • 2011-06-16
          • 1970-01-01
          • 2019-11-08
          • 2013-05-15
          • 1970-01-01
          • 2020-04-10
          • 1970-01-01
          • 2023-03-13
          相关资源
          最近更新 更多