我有用户角色参数
declare @UserRoles varchar (200)
set @UserRoles = '1,2,3'
我想检查一下这样的where子句
SELECT * FROM Request where Role IN (@UserRole)
Role列是一个整数,这会导致错误,因为@UserRole被认为是字符串而不是一堆逗号分隔的整数。反正有没有这样做?
更新
我之所以需要这样做是因为每个用户都有多个角色。他需要根据自己的角色和地位来查看记录。我需要能够创建一个看起来像这样的查询。
(
-- Get All Request Created By User
(r.RequestedBy=@Username)
OR
-- Get All Request Assigned To Role1
(5 in (@UserRoles) and rs.StatusID IN (1))
OR
-- Get All Request Assigned To Role2
(6 in (@UserRoles) and rs.StatusID IN (2))
OR
-- Get All Request Assigned To Role3
(1 in (@UserRoles) and rs.StatusID IN (7,8))
)
答案 0 :(得分:0)
因此,表值函数可以帮助将角色字符串拆分成行,然后你可以进行选择,如下所示:
CREATE FUNCTION [dbo].[SplitString] ( @string NVARCHAR(MAX) )
RETURNS @retVal TABLE ( val NVARCHAR(MAX) )
AS
BEGIN
INSERT INTO @retVal
( val
)
SELECT split.a.value('.', 'VARCHAR(MAX)') AS String
FROM ( SELECT CAST ('<M>' + REPLACE(@string, ',',
'</M><M>')
+ '</M>' AS XML) AS string
) AS A
CROSS APPLY String.nodes('/M') AS split ( a );
RETURN;
END;
GO
然后这样的事情会起作用:
DECLARE @values TABLE
(
[request] NVARCHAR(MAX) ,
[role] NVARCHAR(MAX)
);
INSERT INTO @values
( [request], [role] )
VALUES ( N'A', N'1' ),
( N'B', N'2' ),
( N'C', N'2' ),
( N'D', N'4' ),
( N'E', N'5' ),
( N'F', N'6' );
SELECT *
FROM @values
WHERE [role] IN ( SELECT *
FROM dbo.SplitString('2,3,4') );
如果你通过字符串&#39; 2,3,4&#39;例如,它将返回表中的值:
请求|作用
B | 2
C | 2
D | 4