无法从存储过程 IN 子句提取数据



我正在尝试执行存储过程,但无法从中获取数据。 以下是存储程序。

USE test
GO
CREATE PROCEDURE SELECT_IDs @idList nvarchar(1750)
AS
BEGIN TRY
SELECT DISTINCT child FROM example WHERE parent IN (@idList)
UNION
SELECT DISTINCT parent FROM example WHERE child IN (@idList)
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber;
END CATCH
GO
EXEC SELECT_IDs @idList = ['100','101'];

执行上述过程后,它没有给我任何数据,而就好像我运行相同的选择查询一样,它给了我数据。

SELECT DISTINCT child FROM example WHERE parent IN ('100','101')

阅读评论后,我尝试了以下代码,但不起作用。

/*
Splits string into parts delimitered with specified character.
*/
CREATE FUNCTION [dbo].[SDF_SplitString]
(
@sString nvarchar(2048),
@cDelimiter nchar(1)
)
RETURNS @tParts TABLE ( part nvarchar(2048) )
AS
BEGIN
if @sString is null return
declare @iStart int,
@iPos int
if substring( @sString, 1, 1 ) = @cDelimiter 
begin
set @iStart = 2
insert into @tParts
values( null )
end
else 
set @iStart = 1
while 1=1
begin
set @iPos = charindex( @cDelimiter, @sString, @iStart )
if @iPos = 0
set @iPos = len( @sString )+1
if @iPos - @iStart > 0          
insert into @tParts
values  ( substring( @sString, @iStart, @iPos-@iStart ))
else
insert into @tParts
values( null )
set @iStart = @iPos+1
if @iStart > len( @sString ) 
break
end
RETURN
END

并将存储过程修改为

USE test
GO
CREATE PROCEDURE SELECT_IDs @idList nVarchar(2048)
AS
BEGIN TRY
SELECT DISTINCT child FROM example WHERE parent IN ([dbo].[SDF_SplitString] 
('@idList',',')) or child IN ([dbo].[SDF_SplitString]('@idList',','))
UNION
SELECT DISTINCT parent FROM example WHERE parent IN ([dbo].[SDF_SplitString] 
(@idList,',')) or child IN ([dbo].[SDF_SplitString](@idList,','))
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber;
END CATCH
GO

但是得到的问题:找不到列"dbo"或用户定义的函数或聚合"dbo。SDF_SplitString",或者名称含糊不清。

如果您使用的是SQL Server 2016及更高版本,请尝试使用STRING_SPLIT

USE test GO
CREATE PROCEDURE SELECT_IDs @idList nvarchar(1750) AS BEGIN TRY
SELECT DISTINCT child
FROM example
WHERE parent IN
(SELECT value
FROM STRING_SPLIT(@idList, ','))
UNION
SELECT DISTINCT parent
FROM example
WHERE child IN
(SELECT value
FROM STRING_SPLIT(@idList, ',')) END TRY BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber; END CATCH 
GO
EXEC SELECT_IDs @idList = '100,101';

更新 1.0 - 拆分的积分功能

如下所述修改您的STORED PROCEDURE,您似乎错过了函数调用SELECT子句。

USE test GO
CREATE PROCEDURE SELECT_IDs @idList nVarchar(2048) AS BEGIN TRY
SELECT DISTINCT child
FROM example
WHERE parent IN (SELECT * FROM SDF_SplitString(@idList, ','))
OR child IN (SELECT * FROM SDF_SplitString(@idList, ','))
UNION
SELECT DISTINCT parent
FROM example
WHERE parent IN (SELECT * FROM SDF_SplitString(@idList, ','))
OR child IN (SELECT * FROM SDF_SplitString(@idList, ',')) END TRY BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber; END CATCH GO

最新更新