我无法理解从以下链接引用的选择UDF语句:
How to split a comma-separated value to columns
CREATE FUNCTION dbo.Split (
@InputString VARCHAR(500),
@Delimiter VARCHAR(1)
)
RETURNS @Items TABLE (
Item VARCHAR(500)
)
AS
BEGIN
IF @Delimiter = ' '
BEGIN
SET @Delimiter = ','
SET @InputString = REPLACE(@InputString, ' ', @Delimiter)
END
IF (@Delimiter IS NULL OR @Delimiter = '')
SET @Delimiter = ','
--INSERT INTO @Items VALUES (@Delimiter) -- Diagnostic
--INSERT INTO @Items VALUES (@InputString) -- Diagnostic
DECLARE @Item VARCHAR(500)
DECLARE @ItemList VARCHAR(500)
DECLARE @DelimIndex INT
SET @ItemList = @InputString
SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
WHILE (@DelimIndex != 0)
BEGIN
SET @Item = SUBSTRING(@ItemList, 0, @DelimIndex)
INSERT INTO @Items VALUES (@Item)
-- Set @ItemList = @ItemList minus one less item
SET @ItemList = SUBSTRING(@ItemList, @DelimIndex+1, LEN(@ItemList)-@DelimIndex)
SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
END -- End WHILE
IF @Item IS NOT NULL -- At least one delimiter was encountered in @InputString
BEGIN
SET @Item = @ItemList
INSERT INTO @Items VALUES (@Item)
END
-- No delimiters were encountered in @InputString, so just return @InputString
ELSE INSERT INTO @Items VALUES (@InputString)
RETURN
END -- End Function
GO
我检查了权限,并确保使用以下命令在正确的模式中创建了该函数:
SELECT * FROM INFORMATION_SCHEMA.ROUTINES
但是,当我运行以下内容时,我遇到了问题:
select dbo.Split(TargetFolderId, ',') from ReportConfig where ReportId = 9
错误:
找不到列“dbo”或用户定义的函数或 聚合“dbo.Split”,或名称不明确。
但我能做到
select * from dbo.Split('stringA,stringB', ',')
我们俩正在使用的SSMS版本之间是否存在差异?
我正在使用SQL2017 - SSMS v17.4。
答案 0 :(得分:2)
显然,该函数被定义为表值,你不能像那样使用它
select dbo.Split(TargetFolderId, ',') from ReportConfig where ReportId = 9
但您可以执行CROSS APPLY
来获得TargetFolderId
分割值。
select sp.Item from ReportConfig rc
CROSS APPLY dbo.Split(rc.TargetFolderId) AS sp
where rc.ReportId = 9
答案 1 :(得分:0)
这是你的答案
RETURNS @Items TABLE (
Item VARCHAR(500)
)
在你的代码中,你将返回一个表,所以你必须使用类似这样的函数
Select * FROM dbo.Split('1,2,3,4,5,6',',')
结果
Item
1
2
3
4
5
6