I usually create the samples and test cases on tempdb database. Today, I came a across an issue while working on Sequence object, a new database feature shipped with SQL Server 2012. I tried to use Sequence object from some other database in tempdb database and it gave me given below error message.
Let’s discuss this in detail:
Message Number: 11730
Severity : 16
Error Message: Database name cannot be specified for the sequence object in default constraints.
Error Generation:
In the given below script, I tried to make sequence object (resides in another database (Adventureworks2012)) as a default value of a column in a table. This table resides in tempdb database. Let me create a sample to demonstrate the issue.
--This script is compatible with SQL Server 2012 and above --Create a sequence object in AdventureWorks2012 database. USE [AdventureWorks2012] GO CREATE SEQUENCE [dbo].[Seq_sample] AS [int] START WITH 1 INCREMENT BY 1 GO USE tempdb GO CREATE TABLE dbo.tbl_sample ( [ID] int, [Name] varchar(100) ) GO ALTER TABLE dbo.tbl_sample ADD CONSTRAINT Const_tbl_sample DEFAULT (NEXT VALUE FOR AdventureWorks2012.[dbo].[Seq_Sample]) FOR [ID]; GO --OUTPUT
Msg 11730, Level 15, State 1, Line 2
Database name cannot be specified for the sequence object in default constraints.
Ooopps…… I am unable to make a sequence as a default value in a table if Sequence already resides in another database.
Resolution:
This is the limitiation of a sequence object, that you cannot make any sequence as a default value of a column if it resides in any other database. But there is a way around that you can use to achieve it. So, how can we do it ? You cannot make it as a default but you can still access the sequence even if it is outside your database boundary, using three part name (AdventureWorks2012.[dbo].[Seq_Sample]
). So, using this three part name, you can insert the sequence value in any database. Given below is the sample.
USE tempdb GO CREATE TABLE dbo.tbl_sample ( [ID] int, [Name] varchar(100) ) GO INSERT INTO tbl_sample VALUES (NEXT VALUE FOR AdventureWorks2012.[dbo].[Seq_Sample],'raresql') GO
Leave a Reply