SQL Server中以逗号分隔的操作

时间:2018-01-12 11:08:45

标签: c# sql sql-server sql-server-2017

表1

T1Id      Name    SchoolIds
------------------------------
01        A       1,2,3,4
02        B       4,20,3,1
03        C       20,30,40
04        D       30,20,10,2

表2

T2ID        SchoolIds       Username
--------------------------------------
01          1,2,3,4         a@a.com
02          20,30,40,2      b@a.com
03          30,20,10,2      c@a.com
04          4,20,3,1        d@a.com

有两个页面,一个是登录,另一个是记录。

当某人使用username='a@a.com'登录然后搜索记录时,代码应仅显示Table1中与表1中的列SchoolIds匹配的行。< / p>

如果使用a@a.com登录,则所需的结果为:

T1Id      Name     SchoolIds
-----------------------------
01        A        1,2,3,4
02        B        4,20,3,1
04        D        30,20,10,2

2 个答案:

答案 0 :(得分:3)

首先,不要将项目存储为逗号分隔的字符串。

相反,请转到附加到父表的外键的新表。这也可以让您轻松获得所需的数据。

所以我的建议是创建新表并将每个项目存储为单独的行,并将一些匹配的id存储到父表:)

答案 1 :(得分:1)

看起来很大,但它给出了你想要的东西。是否有任何建议,请注意。

DECLARE @Table1 TABLE(T1ID INT, Name VARCHAR(1), SchoolIds VARCHAR(20))
INSERT INTO @Table1 VALUES(01,'A','1,2,3,4')
INSERT INTO @Table1 VALUES(02,'B','4,20,3,1')
INSERT INTO @Table1 VALUES(03,'C','20,30,40')
INSERT INTO @Table1 VALUES(04,'D','30,20,10,2')

DECLARE @Table2 TABLE(T2ID INT, SchoolIds VARCHAR(20), Username VARCHAR(20))
INSERT INTO @Table2 VALUES(01,'1,2,3,4','a@a.com')
INSERT INTO @Table2 VALUES(02,'20,30,40,2','b@a.com')
INSERT INTO @Table2 VALUES(03,'30,20,10,2','c@a.com')
INSERT INTO @Table2 VALUES(04,'4,20,3,1','d@a.com')


SELECT A.T1ID,Name,
     Split.a.value('.', 'VARCHAR(100)') AS [SchoolId]  
INTO #T1Vals
 FROM  
 (
     SELECT T1ID,Name,
         CAST ('<M>' + REPLACE(SchoolIds, ',', '</M><M>') + '</M>' AS XML) AS Data  
     FROM  @Table1
 ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a);

SELECT A.T2ID,Username,
     Split.a.value('.', 'VARCHAR(100)') AS [SchoolId]  
INTO #T2Vals
 FROM  
 (
     SELECT T2ID, Username,
         CAST ('<M>' + REPLACE(SchoolIds, ',', '</M><M>') + '</M>' AS XML) AS Data  
     FROM  @Table2
     WHERE Username='a@a.com'
 ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a);

 SELECT * 
 FROM @Table1 
 WHERE T1ID IN(
    SELECT T1ID 
    FROM #T1Vals 
    WHERE [SchoolId] IN(SELECT [SchoolId] FROM #T2Vals))

 DROP TABLE #T1Vals
 DROP TABLE #T2Vals

输出:

T1ID    Name    SchoolIds
1       A       1,2,3,4
2       B       4,20,3,1
4       D       30,20,10,2