gpt4 book ai didi

sql - 如何在存储过程中创建索引?

转载 作者:行者123 更新时间:2023-12-02 16:38:02 25 4
gpt4 key购买 nike

如何在存储过程中创建索引?它提示

Msg 102, Level 15, State 1, Procedure createIndexModifiedOn, Line 12
Incorrect syntax near 'PRIMARY'.

但是ON [PRIMARY]如果您创建新索引并选择 Script As New Query,则 SQL Server 本身会使用该索引。 .

如果我删除 ON [PRIMARY]然后它给出了这个错误

Msg 102, Level 15, State 1, Procedure createIndexModifiedOn, Line 12
Incorrect syntax near ')'.

程序如下:

create proc [dbo].createIndexModifiedOn
@table char(256)
as begin
declare @idx char(256)
set @idx = 'idx_' + SUBSTRING(@table, 7, len(@table)-1) + '_modified_on';
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(@table) AND name = @idx)
DROP INDEX [@idx] ON [@table]

CREATE NONCLUSTERED INDEX [@idx] ON [@table]
(
[modified_on] ASC
) ON [PRIMARY]
go

这最终成为完整的查询:

create proc [dbo].createIndexModifiedOn
@table varchar(256)
as
declare @idx varchar(256);
declare @sql nvarchar(999);
set @idx = 'idx_' + SUBSTRING(@table, 8, len(@table)-8) + '_modified_on';
set @sql = '
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(''' + @table + ''') AND name = ''' + @idx + ''')
DROP INDEX [' + @idx + '] ON ' + @table + '

CREATE NONCLUSTERED INDEX [' + @idx + '] ON ' + @table + '
(
[modified_on] ASC
) ON [PRIMARY]
';
print @table + ', ' + @idx;
BEGIN TRY
EXEC sp_executesql @sql;
END TRY
BEGIN CATCH
PRINT 'errno: ' + ltrim(str(error_number()))
PRINT 'errmsg: ' + error_message()
END CATCH
GO

EXEC sp_MSforeachtable 'exec createIndexModifiedOn "?"'

最佳答案

您不能像以前那样在 CREATE INDEX 语句中使用变量。为此,您需要生成 SQL 字符串并使用 sp_executesql 执行它。

手绘示例:

DECLARE @sql NVARCHAR(1024);
SET @sql = 'CREATE NONCLUSTERED INDEX [' + @idx + '] ON [' + @table + ']
(
[modified_on] ASC
) ON [PRIMARY];';
EXEC sp_executesql @sql;

关于sql - 如何在存储过程中创建索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17242597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com