我在名为[T] (varchar(100))
:
AS00516003,QD00516009,XD00516089
如何获取以下字符串以将结果导入 IN 语句:
'AS00516003','QD00516009','XD00516089'
因为如果我使用第一个值执行此查询,则不会获得任何值:
SELECT *
FROM [dbo].[TABLE]
WHERE [NUMBER] IN (SELECT [T] FROM [dbo].[TEST])
答案 0 :(得分:0)
您可以使用String_Split,如下所示:
SELECT [T]
FROM YourTable
CROSS APPLY STRING_SPLIT(Tags, ',');
答案 1 :(得分:0)
您需要动态SQL才能实现:
declare @query varchar(4000)
set @query = 'select * from [dbo].[table] where [number] in ('
--here you will append results from [T] table, all values stored in this table
--will be in the list in WHERE clause of dynamic query
select @query += '''' + REPLACE([T], ',', ''',''') + ''',' from [dbo].[TEST]
--remove last comma and close list with )
set @query = LEFT(@query, len(@query) - 1) + ')'
exec(@query)
答案 2 :(得分:0)
尝试以下脚本
DECLARE @val nvarchar(max)='AS00516003,QD00516009,XD00516089'
,@ReqFormat nvarchar(max)
DECLARE @temp TABLE (Data nvarchar(100))
INSERT INTO @temp
SELECT @val
SELECT * FROM @temp
;WITH CTE
AS
(
SELECT ROW_NUMBER()OVER(ORDER BY (SELECT 1 )) AS Id
,''''+Split.a.value('.','nvarchar(100)')+'''' AS Data
FROM
(
SELECT CAST('<S>'+REPLACE(Data,',','</S><S>')+'</S>' AS XML)Data from @temp
)AS A
CROSS APPLY Data.nodes('S') AS Split(a)
)
SELECT @ReqFormat=STUFF((SELECT ', '+Data FROM CTE
FOR XML PATH ('')),1,1,'')
SELECT @ReqFormat AS ReqFormat
结果
GivenData
-----------------------------------
AS00516003,QD00516009,XD00516089
ReqFormat
----------------------------------------
'AS00516003', 'QD00516009', 'XD00516089'
答案 3 :(得分:0)
您可以将脚本设置为用户定义的函数,如下所示
CREATE FUNCTION [dbo].[udf_GetUnsplitData]
(
@string nvarchar(max)
)
RETURNS @OutTable TABLE
(
DATA nvarchar(max)
)
AS
BEGIN
DECLARE @Temp AS TABLE
(
DATA nvarchar(max)
)
INSERT INTO @Temp
SELECT @string
DECLARE @OutTableInternal AS TABLE
(
DATA nvarchar(max)
)
INSERT INTO @OutTableInternal(DATA)
SELECT
''''+Split.a.value('.','nvarchar(1000)')+'''' As DATA
FROM
(
SELECT
CAST('<S>'+REPLACE(DATA,',','</S><S>')+'</S>' AS XML ) AS DATA
FROM @Temp
)A
CROSS APPLY DATA.nodes('S') AS Split(a)
INSERT INTO @OutTable(DATA)
SELECT STUFF((SELECT ', '+DATA FROM @OutTableInternal
FOR XML PATH ('')),1,1,'')
RETURN
END
SELECT * FROM [dbo].[udf_GetUnsplitData] (
'AS00516003,QD00516009,XD00516089')
GO
结果
DATA
---------------------------------------
'AS00516003', 'QD00516009', 'XD00516089'