动态查询SQL Server 2008中的子查询
如果将以下 select 语句放置在动态查询中,则该语句不起作用。如果它移出动态查询,它工作正常
DECLARE @sid UNIQUEIDENTIFIER , @AttributeID UNIQUEIDENTIFIER
SET @sid = 'c0b5956b-47f2-4ad6-bb9a-67a5a249e4b7'
SET @AttributeID = 'F1A0D9D6-702E-4492-9EBC-63AD22E60E6A'
DECLARE @sql NVARCHAR(MAX)
SET @sql = 'SELECT * FROM
(select [CaseID],
( select
Attr.AttributeValue
from
[dbo].[CV_CaseAttributes] Attr
Where Attr.CaseID = C.CaseID ANd Attr.AttributeID = @AttributeID
) AS CaseTitle
,[UserID]
FROM [dbo].[CaseMaster] C
WHERE SpaceID = @sid
)
AS Details'
EXEC sp_executesql @sql
,N'@sid UNIQUEIDENTIFIER,@AttributeID UNIQUEIDENTIFIER'
,@sid=@sid,@AttributeID =@AttributeID
错误消息
消息 102,级别 15,状态 1,第 2 行
“,”附近的语法不正确。
消息 156,第 15 级,状态 1,第 8 行
关键字“AS”附近的语法不正确。
为什么会这样呢?
The following select statement is not working if it placed inside the dynamic query. It works fine if it moved out of dynamic query
DECLARE @sid UNIQUEIDENTIFIER , @AttributeID UNIQUEIDENTIFIER
SET @sid = 'c0b5956b-47f2-4ad6-bb9a-67a5a249e4b7'
SET @AttributeID = 'F1A0D9D6-702E-4492-9EBC-63AD22E60E6A'
DECLARE @sql NVARCHAR(MAX)
SET @sql = 'SELECT * FROM
(select [CaseID],
( select
Attr.AttributeValue
from
[dbo].[CV_CaseAttributes] Attr
Where Attr.CaseID = C.CaseID ANd Attr.AttributeID = @AttributeID
) AS CaseTitle
,[UserID]
FROM [dbo].[CaseMaster] C
WHERE SpaceID = @sid
)
AS Details'
EXEC sp_executesql @sql
,N'@sid UNIQUEIDENTIFIER,@AttributeID UNIQUEIDENTIFIER'
,@sid=@sid,@AttributeID =@AttributeID
Error Message
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near ','.
Msg 156, Level 15, State 1, Line 8
Incorrect syntax near the keyword 'AS'.
Why is this so ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请使用这个(缺少一个
SELECT
因此会出现错误消息):编辑 - 根据评论:
尝试
编辑 - 根据评论“解释”:
我不是 SQL Server 专家,因此请将以下内容视为猜测:
对我来说,解析器似乎将 EXEC 后面的内容视为新范围。
因此,当按名称解析变量时,它首先在 EXEC 范围内进行检查,如果没有找到要查找的内容,它将搜索扩展到周围范围。
对于原始语句,我们在两个作用域(外部与内部
EXEC
)中有 2 个变量命名相同 - 这会在执行EXEC
内部的代码期间解决这些问题时导致一些问题> 因此不使用 EXEC 外部声明的变量。通过将名称更改为在两个范围内都是唯一的,解析器不再有这些问题......
use this instead (one
SELECT
is missing thus the error message):EDIT - as per comments:
try
EDIT - as per comments an "explanation":
I am no SQL Server expert so please take the following as a guess:
To me it seems that the parser sees things put behind
EXEC
as a new scope.Thus when resolving variables by name it first checks within the scope of
EXEC
and upon not finding what it is looking for it expands the search to the surrounding scope.In case of the original statement we had 2 variables named the same in both scopes (outside versus inside
EXEC
) - this lead to some problem when resolving those during executing the code insideEXEC
and thus not using the declared variables from outside theEXEC
.By changing the names to be unique throughout both scopes the parser no longer had these issues...