1

是否可以在 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 函数的结果

在此处输入图像描述

当我运行上面的代码片段时,出现以下错误

消息 156,级别 15,状态 1,第 15 行
关键字“FROM”附近的语法不正确。

我正在寻找如下

Col1     Col2
1        9
2        8
3        7

是否有另一种方法来定义 Select 语句以返回 Insert 的两个值?

4

3 回答 3

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
于 2013-09-12T10:53:52.483 回答
0

假设您的功能按预期工作

INTO #tmpMeasureCats
SELECT 
    A.value as 'MeasureCat', 
    B.value as 'Snapshot'
FROM 
    dbo.Split(',',@MeasureCategoryIDs) A, 
    dbo.Split(',',@SnapshotIDs) B
于 2013-09-12T10:48:01.163 回答
0
INSERT INTO #tmpMeasureCats
     SELECT value FROM dbo.Split(',',@MeasureCategoryIDs)
INSERT INTO #tmpMeasureCats
SELECT value FROM dbo.Split(',',@SnapshotIDs)
于 2013-09-12T10:48:50.910 回答