sp_executesql没有执行动态sql

时间:2014-05-15 18:25:31

标签: sql sql-server

我想从动态sql中获取两个变量的值。

declare @sImport_Table1 table 
 (
   Id int identity(1,1) ,
   Zone nvarchar(50),
   Sub_Code nvarchar(50),
   Geography nvarchar(50),
   DayOfWeek nvarchar(50)
 )



INSERT INTO @sImport_Table1 SELECT 'A','Z','Geo','SUN'

declare @sZone nvarchar(50)
declare @sSubCode nvarchar(50)
declare @c_Geography nvarchar(50)='Geo'
declare @c_DayOfWeek nvarchar(50)='SUN'
declare @sImport_Table nvarchar(500)='@sImport_Table1'



--SELECT * FROM @sImport_Table1
declare @sQuery nvarchar(4000) 

SET @sQuery='SELECT @sZone = Zone, '+
                   '@sSubCode = Sub_Code
          FROM '+ @sImport_Table +
         ' WHERE Geography ='''+ @c_Geography + '''
          AND [DayOfWeek] = '''+ @c_DayOfWeek +''''

PRINT @sQuery 

sp_executesql @sQuery)

PRINT @sZone 
PRINT @sSubCode    

2 个答案:

答案 0 :(得分:1)

您需要在Dynamic sql中声明此表变量,因为动态sql有自己的作用域,动态sql外部声明的变量在动态sql中不可见。

在尝试从动态sql查询中检索值时也使用OUTPUT子句。像这样......

declare @sZone nvarchar(50)
declare @sSubCode nvarchar(50)
declare @c_Geography nvarchar(50)='Geo'
declare @c_DayOfWeek nvarchar(50)='SUN'
declare @sImport_Table nvarchar(500)='@sImport_Table1'



--SELECT * FROM @sImport_Table1
declare @sQuery nvarchar(MAX); --<-- to be on safe side 

SET @sQuery = N' declare @sImport_Table1 table 
                     (
                       Id int identity(1,1) ,
                       Zone nvarchar(50),
                       Sub_Code nvarchar(50),
                       Geography nvarchar(50),
                       DayOfWeek nvarchar(50)
                     )
               INSERT INTO @sImport_Table1 SELECT ''A'',''Z'',''Geo'',''SUN''

               SELECT @sZone = Zone, @sSubCode = Sub_Code ' +
              N' FROM @sImport_Table1 ' + 
              N' WHERE Geography =  @c_Geography  ' +
              N' AND [DayOfWeek] =  @c_DayOfWeek '

PRINT @sQuery 

EXECUTE sp_executesql @sQuery
                     ,N'@c_Geography nvarchar(50),@c_DayOfWeek nvarchar(50),
                        @sZone nvarchar(50) OUTPUT, @sSubCode nvarchar(50) OUTPUT'
                     ,@c_Geography , @c_DayOfWeek, @sZone OUTPUT, @sSubCode OUTPUT
SELECT @sSubCode, @sZone

答案 1 :(得分:-1)

替换 sp_executesql @sQuery)

执行sp_executesql @sQuery

同样在动态查询中,您需要在动态字符串中声明变量。 否则会抛出错误。