我需要创建一个SQL脚本来确定SQL Server 2012数据库中是否存在序列。我熟悉确定存储过程是否存在而不是序列的过程。谢谢。
答案 0 :(得分:27)
确定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
我希望这有帮助!
答案 1 :(得分:9)
通过检查sys.sequences表中的数据:
select *
from sys.sequences
where object_id = object_id('schema_name.sequence_name')
实际上,如果您确定除了名称等于'schema_name.sequence_name'
的序列之外没有其他对象,您只需检查object_id('schema_name.sequence_name') is not null
<强> sql fiddle demo 强>
答案 2 :(得分:4)
这是Tim S的另一个快捷版本:
IF OBJECT_ID('schema_name.sequence_name', 'SO') IS NOT NULL
BEGIN
DROP SEQUENCE schema_name.sequence_name
END
答案 3 :(得分: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
答案 4 :(得分: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;