【发布时间】:2021-08-23 06:43:58
【问题描述】:
这里我想比较列角色和用户角色的逗号分隔值,然后在另一列中显示匹配的值。
我找到了一个示例compare comma separated values in sql 并使用游标逐行迭代。它对我有用。但我觉得应该有更好的方法来做到这一点。
非常感谢任何帮助。
Create table #temp4
(
user_id int,
permission_id int,
roles varchar(max),
userroles varchar(max),
matchingrolesinthisrow varchar(max))
Insert Into #temp4 values
( 1, -12010, '2341,8760,3546', '1000,1001,1002,1003', null),
( 1, -334, '1002,1001,3467', '2341,1002,3467', null),
( 2, -12349, '9876,9982,6548', '1001,1002,2341', null)
下面是我要找的结果表。
| user_id | permission_id | roles | userroles | matchingrolesinthisrow |
|---|---|---|---|---|
| 1 | -12010 | 2341,8760,3546 | 1000,1001,1002,1003 | |
| 1 | -334 | 1002,1001,3467 | 2341,1002,3467 | 1002,3467 |
| 2 | -12349 | 9876,9982,6548 | 1001,1002,2341 |
到目前为止,我的尝试很有效。请指导我以更好的方式做到这一点。
DECLARE @user_id INT
DECLARE @permission_id INT
DECLARE @roles VARCHAR(MAX)
DECLARE @userroles VARCHAR(MAX)
DECLARE @matchingrolesinthisrow VARCHAR(MAX)
declare cur CURSOR LOCAL for
select user_id, permission_id, roles, userroles, matchingrolesinthisrow from #temp4 order by 1
open cur
fetch next from cur into @user_id, @permission_id, @roles, @userroles, @matchingrolesinthisrow
while @@FETCH_STATUS = 0 BEGIN
print (@roles)
print(@userroles)
--execute on each row
UPDATE #temp4
SET matchingrolesinthisrow = T1.[Item]
FROM [developers].[Split](@roles, ',') AS T1
INNER JOIN [developers].[Split](@userroles, ',') AS T2 on T1.[Item] = T2.[Item]
Where roles = @roles and userroles = @userroles and permission_id = @permission_id and user_id = @user_id
fetch next from cur into @user_id, @permission_id, @roles, @userroles, @matchingrolesinthisrow
END
close cur
deallocate cur
--Split function
CREATE FUNCTION [developers].[Split]
(
@s VARCHAR(max),
@split CHAR(1)
)
RETURNS @temptable TABLE ([Item] VARCHAR(MAX))
AS
BEGIN
DECLARE @x XML
SELECT @x = CONVERT(xml,'<root><s>' + REPLACE(@s,@split,'</s><s>') + '</s></root>');
INSERT INTO @temptable
SELECT [Value] = T.c.value('.','varchar(20)')
FROM @X.nodes('/root/s') T(c);
RETURN
END;
【问题讨论】:
-
请向我们展示您的尝试。
-
@DaleK 添加了我的尝试并仍在尝试。我确信我没有以有效的方式解决这个问题。应该有更好的方法。
-
@DaleK 我更新了我的尝试,到目前为止它对我有用。有没有更好的方法来实现这一目标?任何帮助深表感谢。提前致谢
-
您的 SQL Server 是 2016 还是更高版本?
-
@MarcusViniciusPompeu sql server 2016
标签: sql sql-server tsql split compare