SQL Server:如何解析列值并插入单独表的多列?

时间:2014-03-28 19:53:45

标签: sql sql-server parsing insert

我有一个表CUSTOMER(ID,ADDRESS),其值为

1,ROCKVILLE MDUS 
2,JERSEY CITY NJUS
3,NEW YORK CITY NYUS
.
.
.

我想在单独的表STG_TXN(CITY,STATE,COUNTRY)中加载上述值。 COUNTRY中的最后两个字符,STATE中的后两个字符以及CITY中的所有字符。

ROCKVILLE,MD,US
JERSEY CITY,NJ,US
NEW YORK CITY,NY,US
.
.
.

 INSERT INTO STG_TXN
    SELECT (how can I parse the value to be selected as CITY, STATE and COUNTRY here ? ) 
    FROM dbo.CUSTOMER

3 个答案:

答案 0 :(得分:1)

这应该有效:

INSERT INTO STG_TXN
select 
    LEFT(@teststr,LEN(@teststr)-4) city, 
    LEFT(RIGHT(@teststr,4),2) state, 
    RIGHT(@teststr,2) country 
from customer

答案 1 :(得分:1)

试试这个:

INSERT INTO STG_TXN
select SUBSTRING(address,0,LEN(address) - 4),SUBSTRING(address,LEN(address) - 3,2)
,SUBSTRING(address,LEN(address) - 1,2)
from CUSTOMER

但是,这只适用于州或国家的长度为2

的情况

答案 2 :(得分:0)

另一种选择:

INSERT INTO STG_TXN
select 
substring(address,1, len(address)-4),
reverse(substring(reverse(address),3,2)),
reverse(substring(reverse(address),1,2))
from customer