表值函数,选择多行

时间:2017-06-15 13:20:15

标签: sql sql-server sql-server-2008

我有一个表值函数,它通过一个公共分隔符拆分字符串,并将它们输出到一个具有以下结构的表中:

@ValueLookup TABLE 
(
    Value nvarchar(100),
    ValueIndex int
)

我主要用它来分割组合ID值,例如1234-5678

dbo.SplitString('1234-5678', '-')

目前,我正在使用两个SELECT来获取分割后的两个值,并将它们转换为整数:

DECLARE @FirstID INT
DECLARE @SecondID INT
SELECT 
    @FirstID = CONVERT(INT, Value)
FROM dbo.SplitString('1234-5678', '-')
WHERE ValueIndex = 1
SELECT 
    @SecondID = CONVERT(INT, Value)
FROM dbo.SplitString('1234-5678', '-')
WHERE ValueIndex = 2

有没有办法可以获得这两个值并将它们分配到一个SELECT语句中?

2 个答案:

答案 0 :(得分:1)

declare @FirstId int, @SecondId int;
select 
    @FirstID  = convert(int,min(case when ValueIndex = 1 then Value end))
  , @SecondID = convert(int,min(case when ValueIndex = 2 then Value end))
from dbo.SplitString('1234-5678', '-')

select 
    FirstId  = @FirstId
  , SecondId = @SecondId

rextester演示:http://rextester.com/TRTDI68038

返回:

+---------+----------+
| FirstId | SecondId |
+---------+----------+
|    1234 |     5678 |
+---------+----------+

Demo是使用Jeff Moden的CSV Splitter表值函数完成的,函数名称和输出列已重命名。

拆分字符串参考:

答案 1 :(得分:1)

又一个选择

示例

Declare @String varchar(max) = '1234-5678'
Declare @FirstID INT
Declare @SecondID INT

Select @FirstID  = xDim.value('/x[1]','int')
      ,@SecondID = xDim.value('/x[2]','int')
From  (Select Cast('<x>' + replace(@String,'-','</x><x>')+'</x>' as xml) as xDim) as A