在表变量

时间:2017-05-23 15:52:29

标签: sql-server tsql

我的任务是解决这个问题,但我已经和它斗争了好几天了。任何人都可以帮忙解决它吗?

1,编写T-SQL将以下值插入到表变量中,该变量具有标识列,5个地址行和一个邮政编码列:

-- address line 1: 'Churchill house'
-- address line 2: ' '
-- address line 3: '30 Boston Road'
-- address line 4: ' '
-- address line 5: 'lusaka'
-- postcode: 'e12 3re'

2,编写一个脚本来改变问题1

中表变量中的地址行
-- address line 1: 'Churchill house'
-- address line 2: ' '
-- address line 3: '30 Boston Road'
-- address line 4: ' '
-- address line 5: 'lusaka'
-- postcode: 'e12 3re'

1 个答案:

答案 0 :(得分:1)

第一部分非常简单:

declare @t table (
    id int identity(1,1)
  , address_line_1 varchar(64)
  , address_line_2 varchar(64)
  , address_line_3 varchar(64)
  , address_line_4 varchar(64)
  , address_line_5 varchar(64)
  , postal_code varchar(64)
);

insert into @t values ('Churchill house','','30 Boston Road','','lusaka','e12 3re')

select * from @t

返回:

+----+-----------------+----------------+----------------+----------------+----------------+-------------+
| id | address_line_1  | address_line_2 | address_line_3 | address_line_4 | address_line_5 | postal_code |
+----+-----------------+----------------+----------------+----------------+----------------+-------------+
|  1 | Churchill house |                | 30 Boston Road |                | lusaka         | e12 3re     |
+----+-----------------+----------------+----------------+----------------+----------------+-------------+

取决于你如何定义" shuffle",这可能就足够了:

update @t
set address_line_1 = address_line_2
  , address_line_2 = address_line_3
  , address_line_3 = address_line_4
  , address_line_4 = address_line_5
  , address_line_5 = address_line_1

select * from @t

返回:

+----+----------------+----------------+----------------+----------------+-----------------+-------------+
| id | address_line_1 | address_line_2 | address_line_3 | address_line_4 | address_line_5  | postal_code |
+----+----------------+----------------+----------------+----------------+-----------------+-------------+
|  1 |                | 30 Boston Road |                | lusaka         | Churchill house | e12 3re     |
+----+----------------+----------------+----------------+----------------+-----------------+-------------+

rextester演示:http://rextester.com/WLPAMZ69008