小编典典

使用分隔符向SQL查询添加where子句

sql

我有以下存储过程,该存储过程接受使用两个定界符的字符串。该过程提取数据并将其插入DB。这就像如果我有一个键值对 (示例输入字符串) 说“
10:1,11:2,12:3”,我也需要在 “ Id” 列中寻找值“ 10”并在其中插入值1在 “值” 列等。该过程的代码如下:

ALTER PROCEDURE [SQL_Delimiter_TestProcedure]
@inputStr VARCHAR(MAX) 
AS
BEGIN

DECLARE @t table (val varchar(500))

INSERT INTO @t (val)values (@inputStr)


;WITH CTE AS (
SELECT   
     Split.a.value('.', 'VARCHAR(500)') AS String  
 FROM  (SELECT   
         CAST ('<M>' + REPLACE([val], ',', '</M><M>') + '</M>' AS XML) AS String  
     FROM  @t) AS A CROSS APPLY String.nodes ('/M') AS Split(a))
     INSERT INTO SQL_Delimiter_Test 
     select SUBSTRING(String,0,CHARINDEX(':',String)),REVERSE(SUBSTRING(reverse(String),0,CHARINDEX(':',reverse(String))))  from cte

END

阅读 215

收藏
2021-04-15

共1个答案

小编典典

这是简短的版本:

首先,创建一个用户定义的表类型:

CREATE TYPE KeyValuePair As Table
(
    Key int PRIMARY KEY,
    Value int
)

然后将其用作存储过程中的表值参数:

ALTER PROCEDURE [SQL_Delimiter_TestProcedure]
(
   @KeyValuePair as KeyValuePair readonly
)
AS
BEGIN

INSERT INTO SQL_Delimiter_Test (Id, Value)
SELECT Key, Value
FROM @KeyValuePair

END
2021-04-15