执行失败,因为名称不是一个有效的标识符?

我有一个查询,我需要运行它作为一个dynamic的查询输出一个有意义的列名称。 作为一个例子,如果我直接运行查询,它会正确返回数据。 但是,如果我使用下面的代码,它显示:

The name ' SELECT (CASE WHEN A.Domain IS NOT NULL THEN A.Domain ELSE B.Domain END) AS [Domain], (CASE WHEN A.Email IS NOT NULL THEN A.Email ELSE B.Email END) AS [Email], A.[Sender Size] AS [Sender Size 1], A.[Sender Count] AS [Sender Count 1], A.[Receiver Size] AS [Receiver Size 1], A.[Receiver Count] AS [Receiver Count 1], A.[Sender Size 2] AS [Sender Size 2], A.[Sender Count 2] AS [Sender Count 2], A.[Receiver Size 2] AS [Receiver Size 2], A.[Receiver Count 2] AS [Receiver Count 2], B.SenderSize AS [Sender Size Average], B.SenderCount AS [Sender Count Average], B.ReceiverSize AS [Receiv' is not a valid identifier. 

下面是代码:

 DECLARE @query NVARCHAR(4000) SET @query = N'SELECT * FROM ( SELECT (CASE WHEN A.Domain IS NOT NULL THEN A.Domain ELSE B.Domain END) AS [Domain], (CASE WHEN A.Email IS NOT NULL THEN A.Email ELSE B.Email END) AS [Email], A.[Sender Size] AS [Sender Size 1], A.[Sender Count] AS [Sender Count 1], A.[Receiver Size] AS [Receiver Size 1], A.[Receiver Count] AS [Receiver Count 1], A.[Sender Size 2] AS [Sender Size 2], A.[Sender Count 2] AS [Sender Count 2], A.[Receiver Size 2] AS [Receiver Size 2], A.[Receiver Count 2] AS [Receiver Count 2], B.SenderSize AS [Sender Size Average], B.SenderCount AS [Sender Count Average], B.ReceiverSize AS [Receiver Size Average], B.ReceiverCount AS [Receiver Count Average] FROM ( SELECT (CASE WHEN tf.Domain IS NOT NULL THEN tf.Domain ELSE tf2.Domain END) AS Domain, (CASE WHEN tf.Email IS NOT NULL THEN tf.Email ELSE tf2.Email END) AS Email, ISNULL(tf.SenderSize,0) AS [Sender Size] , ISNULL(tf.SenderCount,0) AS [Sender Count], ISNULL(tf.ReceiverSize,0) AS [Receiver Size], ISNULL(tf.ReceiverCount,0) AS [Receiver Count], ISNULL(tf2.SenderSize,0) AS [Sender Size 2], ISNULL(tf2.SenderCount,0) AS [Sender Count 2], ISNULL(tf2.ReceiverSize,0) AS [Receiver Size 2], ISNULL(tf2.ReceiverCount,0) AS [Receiver Count 2] FROM #TrafficFinal tf FULL JOIN #TrafficFinal2 tf2 ON (tf.Email = tf2.Email AND tf.Domain = tf2.Domain) ) A FULL JOIN #TrafficFinal3 B ON (A.Email = B.Email AND A.Domain = B.Domain) ) C ORDER BY Domain, Email'; PRINT @query; -- run it exec @query; 

是因为完全join吗?

最后试试这个:

 exec (@query) 

如果您没有方括号,则SQL Server将该variables的值设为存储过程名称。

要么

 EXECUTE sp_executesql @query 

而且它不应该是因为FULL JOIN。
但是我希望你已经在这之前创build了临时表:#TrafficFinal,#TrafficFinal2,#TrafficFinal3。


请注意,在使用EXEC和sp_executesql之间有性能方面的考虑。 由于sp_executesql像sp一样使用强制语句caching。
更多细节在这里 。


另一个说明,是否有一个原因,你为什么使用dynamicSQL这种情况下,当你可以使用查询,考虑到你没有做任何查询操作,并按照它的方式执行它?

就像在我的情况下,如果你的SQL是通过连接或使用转换生成的,那么sql在执行时需要用字母N作为前缀如下

例如

 Exec N'Select bla..' 

N定义string文字是unicode。