我的任务是我需要在SQL Server(~370G)中的大表上创建索引。计划是
我可以使用以下脚本在SQL中执行1)和2):
SELECT TOP 0 *
INTO js_sample_indexed
FROM dbo.js_sample
CREATE CLUSTERED INDEX domain_event_platform_idx
ON dbo.js_sample_indexed (domain ASC, event_type ASC, platform ASC)
GO
但我陷入了第三步。据推测,索引中有数千个值,例如,值可能是('亚马逊','搜索','移动')。
所以我可能需要在for循环中放置where语句,同时每次都更新条件以供选择。
但我坚持如何使用SQL存储和检索每列中的值(例如'domain')。
不知道我是否清楚地表达了这个问题,但任何评论都会有所帮助。谢谢!
答案 0 :(得分:0)
我假设桌子上有某种身份字段(用作索引的顺序编号字段)。对于此示例,我将调用此字段ID
。如果这是真的,那么一个简单的循环结构将满足你的需要。
DECLARE @MinID int, @MaxID int, @Step int = 10000 -- Move 10k records per loop
SELECT @MinID = MIN(ID), @MaxID = MAX(ID)
FROM MyTableToCopyFrom
While @@MinID <= @MaxID
BEGIN
INSERT INTO MyTableToCopyTo (Field1, Field2, Field3, Fieldx)
SELECT Field1, Field2, Field3, Field4
FROM MyTableToCopyFrom
WHERE ID >= @MinId
AND ID < @MinId + @Step
SET @MinID = @MinID + @Step
END
答案 1 :(得分:0)
所以我在阅读并询问之后想出了答案。这是代码:
USE jumpshot_data
GO
DROP TABLE dbo.js_indexed
-- create a new table with existing structure
SELECT TOP 0 *
INTO dbo.js_full_indexed_1
FROM dbo.js_test
CREATE CLUSTERED INDEX domain_event_platform_idx
ON dbo.js_full_indexed_1 (domain ASC, event_type ASC, platform ASC)
GO
CREATE NONCLUSTERED INDEX device_id_idx
ON js_full_indexed_1 (device_id ASC);
-- using cursor to loop through meta-data table, and insert by chunk into the new table
DECLARE @event_type varchar(50)
DECLARE @platform varchar(50)
DECLARE @domain varchar(50)
DECLARE SelectionCursor CURSOR LOCAL FOR
SELECT * FROM dbo.js_index_info
OPEN SelectionCursor
FETCH NEXT FROM SelectionCursor into @event_type, @platform, @domain
WHILE (@@FETCH_STATUS = 0)
BEGIN
-- operation at each row
INSERT INTO dbo.js_full_indexed_1
SELECT *
FROM dbo.js_test
WHERE event_type = @event_type AND domain = @domain AND platform = @platform
-- loop condition
FETCH NEXT FROM SelectionCursor into @event_type, @platform, @domain
END
CLOSE SelectionCursor
DEALLOCATE SelectionCursor
GO