且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过一个逗号包含逗号

更新时间:2023-02-18 16:28:45

好的。根据提出的内容。我猜,在存储过程中有一个像'456,678'这样的参数,你想把参数放到查询中,并期望查询返回CPTCode 456和678的行?如果是这种情况,这里是一个例子。



Ok. Based on what presented. I'm guessing, there is a parameter like '456,678' in the Stored Procedure, and you want to put the parameter into the query and expect the query to return the rows with CPTCode 456 and 678? If the the case, here is an example.

DECLARE @temp TABLE  (
 Facility INT IDENTITY(1,1),
 CPTCode VARCHAR(30),
 Something VARCHAR(50)
)

INSERT INTO @temp
	SELECT 45, 'Apple' UNION
	SELECT 46, 'Orange' UNION
	SELECT 456, 'Pear' UNION
	SELECT 577, 'Banana' UNION
	SELECT 678, 'Strawberry'

	--parameter
DECLARE @CptCode  VARCHAR(30)
SET @CptCode  = '45,456,577'

--comma separated string into rows
DECLARE @cptCodeRows TABLE(CPTCode VARCHAR(30));
;WITH CTE_CPTCode
AS
(
    SELECT [xml_val] = CAST('<b>' + REPLACE(@CptCode ,',','</b><b>') + '</b>' AS XML)
)
INSERT INTO @cptCodeRows
	SELECT  
			ProgramId = col.value('.','VARCHAR(30)')
	FROM CTE_CPTCode
	CROSS APPLY [xml_val].nodes('/b') CA(col)

	--get all the records in @CptCode  
SELECT * FROM @temp t JOIN @cptCodeRows c
	ON t.CPTCode = c.CPTCode



输出:


Output:

Facility	CPTCode	  Something	CPTCode
1	        45	      Apple	    45
3	        456	      Pear	    456
4	        577	    Banana	    577


我建​​议您添加一个联结表,而不是在单个列中存储多个外键,而是将每个键存储在单个行中。请参阅多对多(数据模型) - *** [ ^ ]



使用联结表你的查询就像

Instead of storing multiple foreign keys inside a single column, I would recommend adding a junction table where you store each key on an individual row. See Many-to-many (data model) - Wikipedia[^]

Using a junction table your query would simply be something like
SELECT ...
FROM Table1,
     JunctionTable1,
     Test
WHERE JunctionTable1.Facility = Table1.Facility
AND   JunctionTable1.CptCode = Test.CptCode