Identity Problems During Database Creation - sql-server

Using SQL Server Management Studio, my issue stems from a database creation script. The script is written to create a database, many of whose tables have an identity column:
CREATE TABLE Workshop
(
WorkshopID int IDENTITY,
WorkshopName varchar(40) NOT NULL,
Description varchar(800),
CONSTRAINT PK_Workshop PRIMARY KEY (WorkshopID)
);
My issue is that even with the script plainly creating a column as an identity column, after the script runs none of the columns that should be identity columns actually have that column set to be identity.
To clarify: Running the above code will create that table as specified except WorkshopID will not be an identity column.
What needs to change so that the script will work as written?

FYI, if you generate script for this using SQL Management Studio's designer, this is the resulting script:
/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Table_1
(
WorkshopID int NOT NULL IDENTITY (1, 1),
WorkshopName varchar(40) NOT NULL,
Description varchar(800) NULL
) ON [PRIMARY]
GO
ALTER TABLE dbo.Table_1 ADD CONSTRAINT
PK_Table_1 PRIMARY KEY CLUSTERED
(
WorkshopID
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
ALTER TABLE dbo.Table_1 SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
If you create the table and then script it using the Create To... menu option you get a completely different script:
USE [MyDatabase]
GO
/****** Object: Table [dbo].[Workshop] Script Date: 11/27/2012 14:05:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Workshop](
[WorkshopID] [int] IDENTITY(1,1) NOT NULL,
[WorkshopName] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Description] [varchar](800) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_Workshop] PRIMARY KEY CLUSTERED
(
[WorkshopID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

Related

Generating script from existing table having too much detail

When i use SQL Server Management Studio GUI to generate script of a table of an existing database, it produces the following:
USE [BikeStores]
GO
/****** Object: Table [production].[brands2] Script Date: 9/20/2019 3:44:27 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [production].[brands2](
[brand_id] [int] IDENTITY(1,1) NOT NULL,
[brand_name] [varchar](255) NOT NULL,
PRIMARY KEY CLUSTERED
(
[brand_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
But i want the simple table script as follows
CREATE TABLE production.brands2 (
brand_id INT IDENTITY (1, 1) PRIMARY KEY,
brand_name VARCHAR (255) NOT NULL
);
You will not be able to create the desired output in SSMS. However, you can do some slight changes in SSMS of what to output when you script your table. For example you can choose not to
Script Indexes, Triggers and Foreign keys. Etc..
Go to Tools -> Options -> Sql Server Object Explorer -> Scripting

Issue with relationship in SQL Server and Vb.net

I have a table of "CASH PAYMENT". I created two tables in SQL Server 2008 and did drag and drop in vb.net 2010.
Now when I save it with default update code, I get different errors.
I do not have any idea of relationships. I searched the web about it but did not find anything related to it. Also, what code can I use to update my relationship entry for vb.net using SQL Server?
I tried nothing - I only drag and drop the SQL Server database in vb.net and with default update code I got error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_cash-entries_cash-entries". The conflict occurred in database "dbo_main", table "dbo.cash_payn_details", column 'autonumber'
Code is shown below. This is the default code when drag drop SQL Server in vb.net
Me.Validate()
Me.Cash_payn_detailsBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.Dbo_mainDataSet)
Me.Cash_entriesBindingSource.EndEdit()
Me.Cash_entriesTableAdapter.Update(Me.Dbo_mainDataSet)
I want to save two tables with one reference number. I am a beginner in vb.net and SQL Server relationships.
Edit
Table structure:
USE [dbo_main]
GO
/****** Object: Table [dbo].[cash_payn_details] Script Date: 01/04/2019 17:44:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cash_payn_details](
[autonumber] [nchar](10) NOT NULL,
[account] [nchar](10) NULL,
[amount] [nchar](10) NULL,
[date] [nchar](10) NULL,
CONSTRAINT [PK_cash_payn_details] PRIMARY KEY CLUSTERED
(
[autonumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
OTHER IS
USE [dbo_main]
GO
/****** Object: Table [dbo].[cash-entries] Script Date: 01/04/2019 17:45:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cash-entries](
[des_autonumber] [nchar](10) NOT NULL,
[system_ID] [nchar](10) NULL,
[entries] [nvarchar](50) NULL,
CONSTRAINT [PK_cash-entries] PRIMARY KEY CLUSTERED
(
[des_autonumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[cash-entries] WITH CHECK ADD CONSTRAINT [FK_cash-entries_cash-entries] FOREIGN KEY([system_ID])
REFERENCES [dbo].[cash_payn_details] ([autonumber])
GO
ALTER TABLE [dbo].[cash-entries] CHECK CONSTRAINT [FK_cash-entries_cash-entries]
GO
INSERT INTO [dbo_main].[dbo].[cash-entries]
([des_autonumber]
,[system_ID]
,[entries])
VALUES
(<des_autonumber, nchar(10),>
,<system_ID, nchar(10),>
,<entries, nvarchar(50),>)
GO
other is
INSERT INTO [dbo_main].[dbo].[cash_payn_details]
([autonumber]
,[account]
,[amount]
,[date])
VALUES
(<autonumber, nchar(10),>
,<account, nchar(10),>
,<amount, nchar(10),>
,<date, nchar(10),>)
GO

Trigger not triggering

I've got two tables as per diagram below
here is sql script for USERS TABLES
USE [NewUser]
GO
/****** Object: Table [dbo].[USERS] Script Date: 15/12/2014 18:26:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[USERS](
[FirstName] [varchar](50) NULL,
[SureName] [varchar](50) NULL,
[DOB] [date] NULL,
[USID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_USERS] PRIMARY KEY CLUSTERED
(
[USID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
And for ADDRESSES TABLE
USE [NewUser]
GO
/****** Object: Table [dbo].[ADDRESSES] Script Date: 15/12/2014 18:26:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ADDRESSES](
[AID] [int] IDENTITY(1,1) NOT NULL,
[USID] [numeric](18, 0) NULL,
[AddressLine1] [varchar](50) NULL,
[AddressLine2] [varchar](50) NULL,
[PostCode] [varchar](50) NULL,
CONSTRAINT [PK_ADDRESSES] PRIMARY KEY CLUSTERED
(
[AID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[ADDRESSES] WITH CHECK ADD CONSTRAINT [FK_ADDRESSES_USERS]
FOREIGN KEY([USID])
REFERENCES [dbo].[USERS] ([USID])
ON UPDATE CASCADE
ON DELETE SET NULL
GO
ALTER TABLE [dbo].[ADDRESSES] CHECK CONSTRAINT [FK_ADDRESSES_USERS]
GO
After that I have created a TRIGGER using
USE [NewUser]
GO
/****** Object: Trigger [dbo].[autoupdate] Script Date: 15/12/2014 18:33:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[autoupdate]
ON [dbo].[USERS]
AFTER INSERT, DELETE, UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE #TEMPID INT
SET #TEMPID = (SELECT USID FROM INSERTED)
UPDATE ADDRESSES
SET USID = #TEMPID
END
The purpose of the TRIGGER is to insert UID automatically on the second table as soon as a new row is added or updated in first table.
But its not doing what I was expecting it to do.
Screenshots
USERS TABLE
ADDRESSES TABLE
USID from table USERS and AID from table ADDRESSES both has "Is Identity Set to YESS"
I'm assuming this is SQL Server, not MySql - please remove the conflicting RDBMS tag.
With triggers, you'll need to handle set data - the INSERTED and DELETED pseudocolumns are tables, not single rows.
Also, assuming that you aren't going to be updating the PK [USID] on Users, you won't need to handle an UPDATE in the trigger, just INSERT and DELETE, and it looks like you've already decided to handle deletes on user with ON DELETE SET NULL, which will set the USID foreign key to NULL in Addresses.
So this leaves INSERT - I'm guessing here you only want to insert an empty address for new users?:
ALTER TRIGGER [dbo].[autoupdate]
ON [dbo].[USERS]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO ADDRESSES(USID)
SELECT USID FROM INSERTED i
WHERE NOT EXISTS (SELECT 1 FROM ADDRESSES a WHERE a.USID = i.USID)
AND i.USID IS NOT NULL;
END
In order for your trigger to do anything the way you've designed it, you need to have records already in the Addresses table. Once a record exists, it's USID will be updated when a record is updated or inserted in the Users table.

'Incorrect SET Options' Error When Building Database Project

We are using Visual Studio and a database project to generate our database.
I just made a number of database changes (including adding a new table named Correspondence) imported those changes into the database project, and attempted to deploy (rebuild) the database.
When I do, I get the following error:
Creating [dbo].[Correspondence]...
Msg 1934, Level 16, State 1, Server (Server Name), Line 1
CREATE TABLE failed because the following SET options have incorrect settings
: 'ANSI_WARNINGS, ANSI_PADDING'. Verify that SET options are correct for use
with indexed views and/or indexes on computed columns and/or filtered indexes
and/or query notifications and/or XML data type methods and/or spatial index
operations.
Can anyone explain this error to me, and help me resolve it? Here's the script the database project uses to create this table.
PRINT N'Creating [dbo].[Correspondence]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
CREATE TABLE [dbo].[Correspondence] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[WorkbookId] INT NOT NULL,
[ProviderId] UNIQUEIDENTIFIER NOT NULL,
[MessageThreadId] INT NOT NULL,
[MessageThreadType] AS ((1)) PERSISTED NOT NULL
);
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
PRINT N'Creating PK_Correspondence...';
GO
ALTER TABLE [dbo].[Correspondence]
ADD CONSTRAINT [PK_Correspondence] PRIMARY KEY CLUSTERED ([Id] ASC)
WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF,
IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);
GO
According to BOL:
Indexed views and indexes on computed columns store results in the
database for later reference. The stored results are valid only if all
connections referring to the indexed view or indexed computed column
can generate the same result set as the connection that created the
index.
In order to create a table with a persisted, computed column, the following connection settings must be enabled:
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET NUMERIC_ROUNDABORT ON
SET QUOTED_IDENTIFIER ON
These values are set on the database level and can be viewed using:
SELECT
is_ansi_nulls_on,
is_ansi_padding_on,
is_ansi_warnings_on,
is_arithabort_on,
is_concat_null_yields_null_on,
is_numeric_roundabort_on,
is_quoted_identifier_on
FROM sys.databases
However, the SET options can also be set by the client application connecting to SQL Server.
A perfect example is SQL Server Management Studio which has the default values for SET ANSI_NULLS and SET QUOTED_IDENTIFIER both to ON. This is one of the reasons why I could not initially duplicate the error you posted.
Anyway, to duplicate the error, try this (this will override the SSMS default settings):
SET ANSI_NULLS ON
SET ANSI_PADDING OFF
SET ANSI_WARNINGS OFF
SET ARITHABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET NUMERIC_ROUNDABORT OFF
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE T1 (
ID INT NOT NULL,
TypeVal AS ((1)) PERSISTED NOT NULL
)
You can fix the test case above by using:
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
I would recommend tweaking these two settings in your script before the creation of the table and related indexes.
I found the solution for this problem:
Go to the Server Properties.
Select the Connections tab.
Check if the ansi_padding option is unchecked.
In my case I was trying to create a table from one database to another on MS SQL Server 2012. Right-clicking on a table and selecting Script Table as > DROP And CREATE To > New Query Editor Window, following script was created:
USE [SAMPLECOMPANY]
GO
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [FK_Employees_Departments]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
DROP TABLE [dbo].[Employees]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employees](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[DepartmentId] [int] NOT NULL,
[FullName] [varchar](50) NOT NULL,
[HireDate] [datetime] NULL
CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED
(
[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Employees] WITH CHECK ADD CONSTRAINT [FK_Employees_Departments] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Departments] ([DepartmentID])
GO
ALTER TABLE [dbo].[Employees] CHECK CONSTRAINT [FK_Employees_Departments]
GO
However when executing above script it was returning the error:
SELECT failed because the following SET options have incorrect
settings: 'ANSI_PADDING'. Verify that SET options are correct for use
with indexed views and/or indexes on computed columns and/or filtered
indexes and/or query notifications and/or XML data type methods and/or
spatial index operations.
The Solution I've found: Enabling the settings on the Top of the script like this:
USE [SAMPLECOMPANY]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [FK_Employees_Departments]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
DROP TABLE [dbo].[Employees]
GO
CREATE TABLE [dbo].[Employees](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[DepartmentId] [int] NOT NULL,
[FullName] [varchar](50) NOT NULL,
[HireDate] [datetime] NULL
CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED
(
[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Employees] WITH CHECK ADD CONSTRAINT [FK_Employees_Departments] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Departments] ([DepartmentID])
GO
ALTER TABLE [dbo].[Employees] CHECK CONSTRAINT [FK_Employees_Departments]
GO
SET ANSI_PADDING OFF
GO
Hope this help.
For me, just setting the compatibility level to higher level works fine. To see C.Level :
select compatibility_level from sys.databases where name = [your_database]
In my case, I found that a computed column had been added to the "included columns" of an index. Later, when an item in that table was updated, the merge statement failed with that message. The merge was in a trigger, so this was hard to track down! Removing the computed column from the index fixed it.
I had the same issue with the filtered index and my inserts and updates were failing. All I did was to change the stored procedure that had the insert and update statement to:
create procedure abc
()
AS
BEGIN
SET NOCOUNT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_WARNINGS ON
SET ANSI_PADDING ON
end

SQL Server won't let me make column identity

So I have a table in SQL Server w/ a primary key column, and 4 other columns. When I modify the table, and select the primary key column to be identity, it won't let me save the table.
How can I make it an identity column through T-SQL or something without going to the UI?
Thanks.
Here's the create
USE [db]
GO
/****** Object: Table [dbo].[tblMessages] Script Date: 04/05/2011 11:58:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tblMessages](
[messageId] [int] NOT NULL,
[messageText] [varchar](500) NOT NULL,
[messageLatitude] [float] NOT NULL,
[messageLongitude] [float] NOT NULL,
[messageTimestamp] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED
(
[messageId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
You cannot turn an existing column into an IDENTITY column after it's been created.
ALTER TABLE dbo.YourTable
ALTER COLUMN YourColumn INT IDENTITY
will cause an error:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword
'IDENTITY'.
You need to create a new column of type INT IDENTITY and then possibly drop the old one. Or if your table is still empty: drop it and re-create it with the correct settings for your ID column
ALTER TABLE MyTable
ADD NewIdentity INT IDENTITY;
ALTER TABLE MyTable
DROP COLUMN OldPK;
EDIT
If your table is empty, just drop it and add IDENTITY after INT on your PK column and be done with it.

Resources