动态查询不在EXEC上运行

时间:2014-06-20 03:01:05

标签: sql tsql dynamic

在下面的查询中,当我使用print语句时,完整的查询按预期打印出来,我可以拿起它并执行没有问题。但是如果不是打印它,我用EXEC运行它,我得到一个错误 通过获取查询的某些部分并说它是一个不正确的标识符来说错误的语法,就好像执行程序只是看到了部分查询而不是完整的东西。如您所见,我使用的是varchar(max),它应该适合整个查询字符串。有人有任何想法吗?谢谢!

declare @RollUp varchar = "hello"
DECLARE @SQL VARCHAR(MAX) 
SET @SQL =
'INSERT INTO #RESULT 
SELECT CONVERT(VARCHAR,"[Member0].[MEMBER_CAPTION]") AS Zeroth,
CONVERT(VARCHAR,"[Member1].[MEMBER_CAPTION]") AS First,
CONVERT(VARCHAR,"[Member2].[MEMBER_CAPTION]") AS Second,
CONVERT(VARCHAR,"[Member3].[MEMBER_CAPTION]") AS Third,
CONVERT(VARCHAR,"[Member4].[MEMBER_CAPTION]") AS Fourth,
CONVERT(VARCHAR,"[Member5].[MEMBER_CAPTION]") AS Fifth,
CONVERT(VARCHAR,"[Member6].[MEMBER_CAPTION]") AS Sixth,
CONVERT(VARCHAR,"[Member7].[MEMBER_CAPTION]") AS Seventh,
CONVERT(MONEY,"[Measures].[MyMeasure]") AS Eighth
FROM OPENROWSET(''MSOLAP'',''DataSource=MyServer;Initial Catalog=Sales'' ,''    
WITH MEMBER [Measures].[MyMeasure]
AS (SUM (StrToMember("[Trans Date].[Year - Quarter - Month - Date].[Month].&["+ Format(Now(),"yyyyMM") + "]").lag(12)
:StrToMember("[Trans Date].[Year - Quarter - Month - Date].[Month].&["+ Format(Now(),"yyyyMM") + "]").lag(1)    
,[Measures].[Revenue])) 
SELECT NON EMPTY([Measures].[MyMeasure]) on 0,
NON EMPTY({[Commission Category Current].[EP Business Line].[Business Line].members *
[Sales].[Product].members *
[Territory].[Territories].[Territory].members *
[Purchasing Site].[Customers].[Customer].members *
[Purchasing Site].[Cust ID].Children *
[Site].[Customers].[Customer].members *
[Site].[Cust ID].Children} *
[Territory].[Countries].[Territory RollUp].&[''' + @RollUp + ''']
) on 1  FROM SALES
)'''


DECLARE @SQL1 VARCHAR(MAX)= Replace(Replace(@SQL, '[''', '['), ''']', ']')

print @sql1

EXEC @SQL1

2 个答案:

答案 0 :(得分:1)

运行#Result时,表exec未知。它在外部作用域中定义,但不在内部作用域中继承。您不能使用这样的临时表,除非它们是全局临时表(前面有##而不是#)。

此外,如果没有长度,则不应在SQL Server中使用varchar()。默认长度取决于上下文,可能不够长。换句话说,varchar()语句中convert()的长度应为{{1}}。

答案 1 :(得分:0)

我通过分解4个子串中的查询来修复,然后最后只做

EXEC(@ STR1 + @ STR2 + @ STR3 + @ STR4)。

我不确定varchar(max)如何接受一个明显长度不超过1000个字符的动态字符串。除非编辑添加隐藏的字符。

无论如何,修复。