如何将字段的“溢出”与字符限制连接起来

时间:2012-06-15 21:32:11

标签: sql sql-server tsql

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

我需要创建一个查询,使每个地址字段的最大字符数限制为30个字符。如果一个地址字段是> 30然后我将切断剩下的部分,但取余数并将其连接到下一个地址字段的开头。我会这样做,直到最后一个地址字段(address3)被填满,然后才去掉最后一个地址字段的余数。

有没有办法用SQL查询或T-SQL执行此操作?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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