2

我有桌子:

CREATE TABLE [address_tabletype] (
[CONTROL_NUMBER] [varchar](12) NULL,
[ADDRESS1] [varchar](50) NULL,
[ADDRESS2] [varchar](50) NULL,
[CITY] [varchar](50) NULL,
[STATE] [varchar](2) NULL,
[ZIP] [varchar](10) NULL
)
GO

并且,假设我有以下行:

2506387 1   2   3   4   5
2506394 1   2   3   4   5
2506403 1   2   3   4   5

我想看起来像:

2506387|1|2|3|4|5~2506394|1|2|3|4|5~2506403|1|2|3|4|5

我没有尝试过任何事情,因为我真的不知道从哪里开始。

我正在使用 SQL Server 2008 R2,并将使用临时表来构建此字符串。

编辑

我正在使用它传递给绝对需要以这种方式分隔字符串的第 3 方 CLR 函数。我计划将它发送给函数,将其返回给 SP,将其分解为原始形式,然后将结果返回给 SP 的调用者。

谢谢你。

4

2 回答 2

3

尝试以下操作:

SELECT STUFF((select (
    SELECT  '~' + (
        CONTROL_NUMBER+'|'+
        ADDRESS1 +'|'+
        ADDRESS2 + '|'+
        CITY + '|'+
        [States] + '|'+
        ZIP)
    FROM address_tabletype
    FOR XML PATH(''), type
    ).value('text()[1]', 'varchar(max)')), 1, 1, '')
于 2013-08-20T19:59:24.223 回答
0

Basically I would use something like this in your SP:

declare your temp table variable like, note add all the fields you want to it:

declare @rowsToConcat table ([ID] int identity(1,1),[CONTROL_NUMBER] varchar(12), ...repeat for all of your fields)

insert into @rowsToConcat
    select * from [address_tabletype]
declare @loopcnt int
declare @concat_output as varchar(1000)
set @loopcnt = 1
while(@loopcnt < (select max([ID]) from @rowsToConcat))
begin
    select @concat_output = @concat_output + [CONTROL_NUMBER] + '|' + [..all other fields] + '~'
    from @rowsToConcat 
    where [ID] = @loopcnt
    set @loopcnt = @loopcnt+1
end

Just typed this without testing here, I did not fill in all your fields but put ..all other fields for you to repeat. I use this technique a lot works for me. Also haven't tested but you may want to make @concat_output a varchar(max) if you don't know how many results to expect.

于 2013-08-20T20:25:45.317 回答