在SQL Server中复制现有行“n”次

时间:2012-01-09 17:13:49

标签: sql sql-server

如果我有一个带有行的表,我可以在同一个表中插入“x”次,除了几列之外,还可以复制除行中的所有内容。一些事情:

INSERT INTO #tbl
(City, Region, Country)
SELECT 
"Different city", Same region, Same country 5 times.

我试图在不使用循环的情况下这样做。

2 个答案:

答案 0 :(得分:1)

如果你有另一个表中的城市,你可以这样做:

create table #cities (
  city varchar(30)
)

INSERT INTO #cities values ('London')
INSERT INTO #cities values ('Lisbon')
INSERT INTO #cities values ('Paris')
INSERT INTO #cities values ('New York')
INSERT INTO #cities values ('Barcelona')

INSERT INTO #tbl
(City, Region, Country)
SELECT c.city, 'REGION', 'COUNTRY' from #cities c

drop table #cities

答案 1 :(得分:1)

如果您将城市放在单独的表格中,您应该能够执行以下操作:

DECLARE @tbl TABLE (City varchar(20), Region varchar(20), Country varchar(20))
INSERT INTO @tbl
VALUES('Malmo', 'Skane', 'Sweden')

--Borrowing some code from @aF.
DECLARE @cities TABLE (city varchar(20))

INSERT INTO @cities values ('London')
INSERT INTO @cities values ('Lisbon')
INSERT INTO @cities values ('Paris')
INSERT INTO @cities values ('New York')
INSERT INTO @cities values ('Barcelona')

INSERT INTO @tbl
SELECT cities.city, tbl.Region, tbl.Country
FROM (select top 1 Region, Country from @tbl) tbl, @cities cities