2012-06-15 74 views
1

我有一個帶有3個地址字段的表,每個地址字段都有100個字符的限制。如何連接帶有字符限制的字段的「溢出」

我需要創建一個查詢,以使每個地址字段的最大字符限制爲30個字符長。如果一個地址字段大於30,那麼我將切斷其餘的部分,但是將其餘的部分並且連接到下一個地址字段的開頭。我會這樣做,直到最後的地址字段(地址3)被填滿,然後在最後的地址字段中刪除餘數。

有沒有辦法用SQL查詢或T-SQL做到這一點?

+0

如果所有三個地址部分總共使用了15個字符,第二個和第三個字段中將會出現什麼? –

+0

因此,如果address1是15個字符,我會保持原樣。但是,如果地址2是35,我會將最後5個字符放在地址3的開頭。 – Chad

+0

不幸的是,這使得它更難。讓我看看我能不能做點什麼。 –

回答

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 
+0

此解決方案的工作方式非常魅力! **謝謝!** – Chad

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 | 

如果不是什麼你正在尋找請爲上述指定所需的輸出。

UPDATE:

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

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 
+0

所以這裏所需的輸出是...'id | f | s | t 1 | abcdefghijklmnopqrstuvwxyz123 | 456789第二部分|第三部分' – Chad

+0

Yah這是一個好的開始。我正在尋找一些使用T-SQL或其他東西的更加動態的東西。也許需要使用遊標。 – Chad