SQL Server:SELECT * INTO需要永远运行

时间:2016-01-14 11:10:27

标签: sql-server tsql

我正在尝试使用SELECT INTO语句使用如下语法生成临时表:

SELECT [FirstName], [LastName], [Zipcode]
INTO [PeopleAndPlaces]
FROM [FirstNames] F
LEFT JOIN [LastNames] L  on F.ID = L.ID
LEFT JOIN [ZipCodes] Z on Z.ID = L.ID

此查询似乎无限期运行(现在超过2小时没有结果)。但是,如果我只运行一个select语句:

SELECT [FirstName], [LastName], [Zipcode]
--INTO [PeopleAndPlaces]
FROM [FirstNames] F
LEFT JOIN [LastNames] L  on F.ID = L.ID
LEFT JOIN [ZipCodes] Z on Z.ID = L.ID

查询在约4分钟内完成。这怎么可能?

作为一个额外的检查,我尝试运行查询以获得更小的集合,包括和不包含into子句:

SELECT [FirstName], [LastName], [Zipcode]
INTO [PeopleAndPlaces]
FROM [FirstNames] F
LEFT JOIN [LastNames] L  on F.ID = L.ID
LEFT JOIN [ZipCodes] Z on Z.ID = L.ID;
WHERE [Zipcode] = '1000'

SELECT [FirstName], [LastName], [Zipcode]
--INTO [PeopleAndPlaces]
FROM [FirstNames] F
LEFT JOIN [LastNames] L  on F.ID = L.ID
LEFT JOIN [ZipCodes] Z on Z.ID = L.ID
WHERE [Zipcode] = '1000'

这两个查询都需要大约10秒才能完成,这让我相信表格的创建并不一定比简单地显示结果花费更长的时间。

1 个答案:

答案 0 :(得分:0)

您提到您正在尝试创建临时表,但我在#之前没有看到必需的[PeopleAndPlaces]。尝试将您的查询更新为:

SELECT [FirstName], [LastName], [Zipcode]
INTO [#PeopleAndPlaces]
FROM [FirstNames] F
LEFT JOIN [LastNames] L  on F.ID = L.ID
LEFT JOIN [ZipCodes] Z on Z.ID = L.ID

更新,我在我的数据库中尝试了你的查询版本,它不会永远运行,所以我会查看你的结果集。这需要多长时间才能运行?

SELECT *
FROM [FirstNames] F
LEFT JOIN [LastNames] L  on F.ID = L.ID
LEFT JOIN [ZipCodes] Z on Z.ID = L.ID