1

我有一个包含 3 个地址字段的表,每个地址字段的限制为 100 个字符。

我需要创建一个查询以使每个地址字段的最大字符限制为 30 个字符。如果一个地址字段大于 30,那么我将切断其余部分,但将剩余部分连接到下一个地址字段的开头。我会这样做,直到最后一个地址字段(address3)被填满,然后摆脱最后一个地址字段的剩余部分。

有没有办法通过 SQL 查询或 T-SQL 来做到这一点?

4

2 回答 2

3

您没有指定如何处理非常短的地址,但我的第一次破解是这样的:

with temp as
(
  select 1 id, 'abcdefghijklmnopqrstuvwxyz123456789' part1, 'second part' part2, 'third part' part3
),
 concated as
(
  SELECT id, part1 + part2 + part3 as whole
  FROM temp
)
select  id, 
        SUBSTRING(whole, 0, 30) f, 
        SUBSTRING(whole, 30,30) s, 
        SUBSTRING(whole, 60,30) t 
from concated

这将返回:

id  | f                               | s                            | t
1   | abcdefghijklmnopqrstuvwxyz123   | 456789second partthird part  |  

如果这不是您要查找的内容,请为上述内容指定所需的输出。

更新:

嗯......这似乎工作,但它很恶心。我相信有人可以提出更好的解决方案。

with temp as
(
  select 1 id, 'abcdefghijklmnopqrstuvwxyz123456789 ' part1, 'second part' part2, 'third part' part3
)
select  id, 
        SUBSTRING(part1, 0, 30) f, 
        SUBSTRING(SUBSTRING(part1, 30, 70) + SUBSTRING(part2, 0,30),0,30) s, 
        SUBSTRING(SUBSTRING(SUBSTRING(SUBSTRING(part1, 30, 70) + SUBSTRING(part2, 0,30),30,70),0,30) + SUBSTRING(part3, 0,30),0,30) t 
from temp
于 2012-06-15T21:46:49.683 回答
1

我想我会按照问题描述去写一些“显然”正确的东西(前提是我已经理解了你的规范:-))

/* Setup data - second example stolen from Abe, first just showing that it works with short enough data */
declare @t table (ID int not null,Address1 varchar(100) not null,Address2 varchar(100) not null,Address3 varchar(100) not null)
insert into @t (ID,Address1,Address2,Address3)
values (1,'abc','def','ghi'),
(2,'abcdefghijklmnopqrstuvwxyz123456789 ', 'second part', 'third part')

/* Actual query - shift address pieces through the address fields, but only to later ones */
;with Shift1 as (
    select
        ID,SUBSTRING(Address1,1,30) as Address1,SUBSTRING(Address1,31,70) as Address1Over,Address2,Address3
    from @t
), Shift2 as (
    select
        ID,Address1,SUBSTRING(Address1Over+Address2,1,30) as Address2,SUBSTRING(Address1Over+Address2,31,70) as Address2Over,Address3
    from Shift1
), Shift3 as (
    select
        ID,Address1,Address2,SUBSTRING(Address2Over+Address3,1,30) as Address3
    from Shift2
)
select * from Shift3

结果:

ID            Address1                          Address2                          Address3
----------- ------------------------------ ------------------------------ ------------------------------
1           abc                                 def                                ghi
2           abcdefghijklmnopqrstuvwxyz1234   56789 second part                 third part
于 2012-06-17T05:17:41.560 回答