是否可以在select语句中返回两个函数调用的结果?
我有下面的TSQL剪辑,接受两个csv字符串,我想按顺序插入临时表。 dbo.Split
获取字符串并返回值表。
段
DECLARE @MeasureCategoryIDs as nvarchar(100)
DECLARE @SnapshotIDs as nvarchar(100)
SET @MeasureCategoryIDs = '1,2,3'
SET @SnapshotIDs = '9,8,7'
CREATE TABLE #tmpMeasureCats
(
MeasureCatID int PRIMARY KEY NOT NULL,
SnapshotID int NOT NULL
)
INSERT INTO #tmpMeasureCats
SELECT value FROM dbo.Split(',',@MeasureCategoryIDs), value FROM dbo.Split(',',@SnapshotIDs)
DROP TABLE #tmpMeasureCats
分割
ALTER FUNCTION [dbo].[Split]
( @Delimiter varchar(5),
@List varchar(8000)
)
RETURNS @TableOfValues table
( RowID smallint IDENTITY(1,1),
[Value] varchar(50)
)
AS
BEGIN
DECLARE @LenString int
WHILE len( @List ) > 0
BEGIN
SELECT @LenString =
(CASE charindex( @Delimiter, @List )
WHEN 0 THEN len( @List )
ELSE ( charindex( @Delimiter, @List ) -1 )
END
)
INSERT INTO @TableOfValues
SELECT substring( @List, 1, @LenString )
SELECT @List =
(CASE ( len( @List ) - @LenString )
WHEN 0 THEN ''
ELSE right( @List, len( @List ) - @LenString - 1 )
END
)
END
RETURN
END
在两个csv字符串上调用split函数的结果
当我运行上面的代码段时,我收到以下错误
第15行,第15行,第1行,第15行 关键字“FROM”附近的语法不正确。
我正在寻找的是
Col1 Col2
1 9
2 8
3 7
是否有另一种方法可以将Select语句用来返回Insert的两个值?
答案 0 :(得分:3)
INSERT INTO #tmpMeasureCats(MeasureCatID, SnapshotID)
select t1.value, t2.value
from
(SELECT value, row_number() over (order by (select 1)) rn FROM dbo.Split(',',@MeasureCategoryIDs)) t1
join
(SELECT value, row_number() over (order by (select 1)) rn FROM dbo.Split(',',@SnapshotIDs)) t2
on t1.rn = t2.rn
答案 1 :(得分:0)
假设您的功能按预期工作
INTO #tmpMeasureCats
SELECT
A.value as 'MeasureCat',
B.value as 'Snapshot'
FROM
dbo.Split(',',@MeasureCategoryIDs) A,
dbo.Split(',',@SnapshotIDs) B
答案 2 :(得分:0)
INSERT INTO #tmpMeasureCats
SELECT value FROM dbo.Split(',',@MeasureCategoryIDs)
INSERT INTO #tmpMeasureCats
SELECT value FROM dbo.Split(',',@SnapshotIDs)