2

这有点令人困惑,因为它之前工作过,我添加了 1 个小改动,我在我的 Web 应用程序中收到了这个错误消息。(我确实有其他案例,为简单起见,我只是取出了其他案例)

之前工作的原始代码:

ALTER PROCEDURE [dbo].[GetRoles]
(@reportid Decimal, @dom varchar(10))

AS
DECLARE @sql varchar(2000) 
SELECT @sql = 
Case @reportid

WHEN 1 THEN
 'select u.id as userId, u.domain, u.isAdmin, u.email, u.canReport, a.[site], a.bldgNum,  a.dataCenterNum, l.shortName, l.[description], a.canApprove, a.canComplete
    from locAdmin a
    inner join location l on  (a.site=l.site and a.bldgNum = l.bldgNum and a.dataCenterNum = l.dataCenterNum)
    right outer join [user] u on u.id=a.userId and u.domain=a.domain
    where u.isAdmin = 1'
End

EXEC (@sql)

我做的唯一改变是添加

and u.domain = @dom'

在最后的 u.isAdmin = 1' 之后,看起来像这样

where u.isAdmin = 1 and u.domain = @dom'
4

3 回答 3

1

您不需要动态 SQL 来编写此查询。

请这样做:

ALTER PROCEDURE [dbo].[GetRoles]
(
   @reportid Decimal,
   @dom varchar(10)
)
AS

 select u.id as userId, u.domain, u.isAdmin, u.email, u.canReport, 
        a.[site], a.bldgNum,  a.dataCenterNum, 
        l.shortName, l.[description],
        a.canApprove, a.canComplete
 from locAdmin a
 inner join location l
    on a.site=l.site and a.bldgNum = l.bldgNum and a.dataCenterNum = l.dataCenterNum
 right outer join [user] u 
    on u.id=a.userId and u.domain=a.domain
 where u.isAdmin = 1 and u.domain = @dom and @reportid = 1
于 2012-08-12T18:50:28.060 回答
1

您需要@dom在执行动态 SQL 时添加为参数。

替换EXEC (@sql)exec sp_executesql @sql, N'@dom varchar(10)', @dom并更改DECLARE @sql varchar(2000)DECLARE @sql nvarchar(2000)

于 2012-08-12T13:55:53.440 回答
1

您需要将变量的值实际添加到动态 SQL 中:

'THE REST OF YOUR QUERY
where u.isAdmin = 1 and u.domain = ''' + @dom + ''''

这是因为您的动态 SQL 是您要执行的另一个 SQL 语句,因此不知道@dom原始语句中的参数。

于 2012-08-10T19:53:43.177 回答