在SQL Server 2005中将字符串拆分为三个变量

时间:2011-12-14 19:50:20

标签: sql-server

我有一个字符串

declare @s varchar(100),
set @s='aaaa,bbbb,cccc'

declare @first varchar(100),
declare @second varchar(100),
declare @third varchar(100)

现在我需要将这些字符串拆分为三个变量,保存像这样的值

@first=aaaa
@second=bbbb
@third=cccc

如果我正在使用split函数,那么我得到像这样的输出

aaaa
bbbb
cccc

我们有更好的方法可以达到这个结果吗?任何帮助将不胜感激。

我希望这个结果变成一个变量,因为我需要它进行进一步处理

由于

3 个答案:

答案 0 :(得分:3)

这是一个快速而肮脏的黑客,假设您的输入字符串始终遵循该格式。

DECLARE @s VARCHAR(100)
SET @s = 'aaaa,bbbb,cccc'


DECLARE @first VARCHAR(100)
DECLARE @second VARCHAR(100)
DECLARE @third VARCHAR(100) 

SET @s = '<row>' + REPLACE(@s, ',', '</row><row>') + '</row>'

SELECT  @first = CONVERT(XML, @s).value('(/row)[1]', 'varchar(100)')
      , @second = CONVERT(XML, @s).value('(/row)[2]', 'varchar(100)')
      , @third = CONVERT(XML, @s).value('(/row)[3]', 'varchar(100)')
SELECT  @first
      , @second
      , @third

答案 1 :(得分:1)

如果您正在使用的split函数返回表中的三个值,则一个选项可能是使用该输出插入具有整数标识的表变量,然后选择具有哪个标识值的变量对: / p>

DECLARE @first VARCHAR(100)
DECLARE @second VARCHAR(100)
DECLARE @third VARCHAR(100) 

declare @split_output table (block varchar(100) )

declare @split_identity table (in_order int identity(1,1), block varchar(100))


/* recreate output of split fn */
insert into @split_output
select 'aaaa'
union
select 'bbbb'
union
select 'cccc'

select * from @split_output


/* push split output into table with identity column */
insert into @split_identity (block)
select block from @split_output

select * from @split_identity


/* Use identity value to pick which row of the table goes with which variable */
set @first = (select block from @split_identity where in_order = 1)
set @second = (select block from @split_identity where in_order = 2)
set @third  = (select block from @split_identity where in_order = 3)

select @first, @second, @third

答案 2 :(得分:0)

declare @s varchar(100)
set @s='aaaa,bbbb,cccc'

declare @first varchar(100)
declare @second varchar(100)
declare @third varchar(100)

select @first = left(@s, T.C1-1),
       @second = substring(@s, T.C1+1, T.C2-T.C1),
       @third = stuff(@s, 1, T.C2+1, '')
from (select charindex(',', @s),
             len(@s)-charindex(',', reverse(@s))) as T(C1, C2)

String Functions (Transact-SQL)