我需要创建一个 SQL 脚本来确定 SQL Server 2012 数据库中是否存在序列。我熟悉确定存储过程是否存在但不序列的过程。谢谢你。
问问题
49191 次
5 回答
34
用于确定 SQL Server 2012 中是否存在序列的脚本与检查存储过程非常相似。考虑以下检查存储过程是否存在的代码:
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[SProc_Name]') AND type IN (N'P', N'PC')
类型的“P”和“PC”值指定 sys.object 的类型是 SQL 存储过程或程序集 (CLR) 存储过程。要检查一个序列,您只需将其更改为“SO”,这表明它是一个序列对象:
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[Sequence_Name]') AND type = 'SO'
例如,如果你想创建一个不存在的序列,你可以使用下面的代码:
IF NOT EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Sequence_Name]') AND type = 'SO')
CREATE SEQUENCE [dbo].[Sequence_Name]
AS [bigint]
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 9223372036854775807
CACHE 3
GO
我希望这有帮助!
于 2013-09-26T18:45:11.823 回答
11
通过检查sys.sequences表中的数据:
select *
from sys.sequences
where object_id = object_id('schema_name.sequence_name')
实际上,如果您确定除了名称为 equals 的序列之外没有其他对象'schema_name.sequence_name'
,您可以检查object_id('schema_name.sequence_name') is not null
于 2013-09-26T18:37:23.963 回答
9
这是 Tim S 的另一个快捷版本:
IF OBJECT_ID('schema_name.sequence_name', 'SO') IS NOT NULL
BEGIN
DROP SEQUENCE schema_name.sequence_name
END
于 2016-09-15T05:45:56.980 回答
3
尝试这个。这将列出给定数据库的所有序列。
SELECT
seq.name AS [Sequence Name],
seq.object_id AS [Object ID],
seq.create_date AS [Creation Date],
seq.modify_date AS [Last Modified Date],
SCHEMA_NAME(seq.schema_id) AS [Schema],
CAST(seq.precision AS int) AS [Numeric Precision],
CAST(seq.scale AS int) AS [Numeric Scale],
ISNULL(seq.start_value,N'''') AS [Start Value],
ISNULL(seq.increment,N'''') AS [Increment Value],
ISNULL(seq.minimum_value,N'''') AS [Min Value],
ISNULL(seq.maximum_value,N'''') AS [Max Value],
CAST(seq.is_cycling AS bit) AS [Is Cycle Enabled],
ISNULL(seq.cache_size,0) AS [Cache Size],
ISNULL(seq.current_value,N'''') AS [Current Value]
FROM sys.sequences AS seq
于 2013-10-01T14:52:02.293 回答
2
我正在使用 SQL Server 17.4(MS SQL Sever 的最新版本),并且这个 SQL 脚本与我一起工作。例如,此 SQL 脚本会在不存在时创建序列。
IF NOT EXISTS
(
SELECT [name]
FROM sys.sequences
WHERE [name] = 'seq_businessTripRequest'
)
BEGIN
CREATE SEQUENCE [dbo].[seq_businessTripRequest]
AS [BIGINT]
START WITH 1
INCREMENT BY 1
MINVALUE-9223372036854775808
MAXVALUE 9223372036854775807
CACHE;
END;
于 2017-12-18T08:46:24.923 回答