无法用逗号分隔int列?

时间:2014-08-26 10:14:16

标签: sql sql-server

我有一些具有角色的表和另一个具有角色和权限映射的表。 我创建了以下SQL来获取以逗号分隔的权限,这不存在于给定的permissionid字符串

DECLARE @RoleToDelete VARCHAR(500), @Permission_Ids VARCHAR(400) = '1,2,5,6,8'
DECLARE @SQL NVARCHAR(500) 
SET @SQL = 'SELECT @RoleToDelete = coalesce(@RoleToDelete + '','', '''') + CAST(a.PermissionId AS VARCHAR)
FROM (SELECT PermissionId from [dbo].[RolePermissions] where RoleId = 11063 and PermissionId not in (' + @Permission_Ids +')) a'
EXECUTE @SQL
PRINT @RoleToDelete

上面的代码将返回权限编号,这些编号在角色11063的@Permission_Ids字符串中未提及。

我收到以下错误

The name 'SELECT @RoleToDelete = coalesce(@RoleToDelete + ',', '') + CAST(a.PermissionId AS VARCHAR)
FROM (SELECT PermissionId from [dbo].[RolePermissions] where RoleId = 11063 and PermissionId not in (1,2,5,6,8)) a' is not a valid identifier.

2 个答案:

答案 0 :(得分:2)

您正在寻找例行程序sp_executesql。这允许您从动态SQL语句返回值。我认为以下内容可行:

DECLARE @RoleToDelete VARCHAR(500) = '', @Permission_Ids VARCHAR(400) = '1,2,5,6,8';
DECLARE @SQL NVARCHAR(MAX);

SET @SQL = 'SELECT @RoleToDelete = coalesce(@RoleToDelete + '','', '''') + CAST(a.PermissionId AS VARCHAR)
FROM (SELECT PermissionId from [dbo].[RolePermissions] where RoleId = 11063 and PermissionId not in (' + @Permission_Ids +')) a';

exec sp_executesql @SQL, N'@RoleToDelete varchar(8000) OUTPUT', @RoleToDelete = @RoleToDelete OUTPUT;

PRINT @RoleToDelete;

答案 1 :(得分:1)

使用EXECUTE运行sql的两种方法之间存在非常细微的区别。运行:

EXECUTE @SQL

尝试运行名称为@SQL的存储过程。运行:

EXECUTE (@SQL)

将运行@SQL中包含的实际SQL。切换到后者解决您的问题;这可能会引发与您的语法相关的另一个错误,但这应该更容易修复。