[英]Comma-separated operation in SQL Server
Table 1 : 表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
Table 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
There are two pages, one is login and other is records. 有两个页面,一个是登录页面,另一个是记录页面。
When someone is logging in with username='a@a.com'
and then goes for records, then the code should display only those rows from Table1
which are a match with columns SchoolIds
from Table 1. 当某人使用
username='a@a.com'
登录并进行记录时,该代码应仅显示Table1
中的那些行与Table1
1中SchoolIds
列的匹配项。
if login with a@a.com
the desired result would be: 如果使用
a@a.com
登录,则期望的结果将是:
T1Id Name SchoolIds
-----------------------------
01 A 1,2,3,4
02 B 4,20,3,1
04 D 30,20,10,2
First of all, do not store items as comma separated string. 首先,不要将项目存储为逗号分隔的字符串。
Instead, go for a new table with foreign keys attached to the parent table. 相反,请转到一个新表,该表具有附加到父表的外键。 That will also allow you to easily get the required data.
这也将使您轻松获得所需的数据。
So my advice is to create new table and store each item as separate rows with some matching id to parent table :) 所以我的建议是创建一个新表并将每个项目存储为单独的行,并与父表匹配一些ID :)
It seems Big, But it gives what you want. 看起来很大,但是却能提供您想要的东西。 Is any suggestions, kindly put in the comments.
有任何建议,请在评论中注明。
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
Output: 输出:
T1ID Name SchoolIds
1 A 1,2,3,4
2 B 4,20,3,1
4 D 30,20,10,2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.