存储过程中的动态SQL执行错误

时间:2016-11-11 16:59:37

标签: sql sql-server tsql stored-procedures

我想在存储过程中执行动态SQL,即使它与静态SQL一起工作也会引发错误。只是想知道在我的存储过程中运行动态SQL的最佳方法是什么?

评论: -

此sql存在于一个存储过程SP2中,并且从另一个存储过程SP1调用,其中临时表正在SP2中创建和使用。静态sql工作正常,但是当我尝试通过存储过程动态运行时,它失败了。

执行: -

execute sp_executesql @inputsql_1, N'@newInputTableName NVARCHAR(100)';

错误: -

Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'.

动态SQL:

SET @inputsql_1 = 'INSERT INTO #tlocationinput(locationsid,contractsid,locationid,locationname,address,city,areascheme,intarealevel1,strarealevel2,strarealevel3,strarealevel4,strareabriefnamel1,strareabriefnamel2,strareabriefnamel3,strareabriefnamel4,zip9,subarea2,cresta,latitude,longitude,streetnumber,streetname,streettype,prefix,suffix,streettypeex )
 SELECT  locationsid
       , contractsid
       , locationid
       , locationname
       , address
       , city 
       , COALESCE( NULLIF(areascheme,0),
                   CASE WHEN LEN(i.postalarea) > 0 THEN 1003
                        WHEN LEN(i.subarea) > 0  THEN 1001
                        WHEN LEN(i.area) > 0 THEN 1000
                     END
                  ) AS areascheme
       , COALESCE(l.country, CASE WHEN i.country in (''US'') THEN 1 ELSE NULL END) AS intarealevel1
       , s.area AS strarealevel2
       , COALESCE(l.subarea, i.subarea) AS strarealevel3
       ,  REPLICATE(''0'',5) + SUBSTRING( i.postalarea,1,5 ) AS strarealevel4      
       , COALESCE(l.country_cd, i.country) AS strareabriefnamel1
       , COALESCE(l.state_cd, i.area)   AS strareabriefnamel2
       , null AS strareabriefnamel3
       , null AS strareabriefnamel4
       , CASE WHEN LEN(i.postalarea) > 5 THEN i.postalarea ELSE NULL END AS zip9
       , subarea2
       , cresta
       , latitude
       , longitude
       , streetnumber
       , streetname
       , streettype
       , prefix
       , suffix
       , streettypeex
FROM @newInputTableName i
left outer join 
     airgeography.dbo.tcountrylookup l on ( i.country = l.country_cd and  ( REPLICATE(''0'',5) + SUBSTRING( i.postalarea,1,5 ) ) = l.postal_area)
left outer join 
     #statelookup s on ( i.country = s.country_cd and s.state_cd = i.area );'

0 个答案:

没有答案