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.
Related
Im trying to use Linqpad so as to use LINQ instead of TSQL when trying to remove some records from a table that is part of a "dependency tree" that spans probably 10-12 tables. So I created some tables in a test db and im experimenting with the DeleteAllOnSubmit and SubmitChanges methods.
I get an FK error. Yet, Im deleting the child objects first. How do I delete when there is FK relations (without using cascading on the FK's)?
The DELETE statement conflicted with the REFERENCE constraint
"FK_OrderItem_Order". The conflict occurred in database "Test", table
"dbo.OrderItem", c...
Tables:
USE [Test]
GO
/****** Object: Table [dbo].[Order] Script Date: 6/9/2016 2:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Order](
[Id] [int] IDENTITY(1,1) NOT NULL,
[OrderNum] [varchar](20) NOT NULL,
[Description] [varchar](100) NULL,
CONSTRAINT [PK_Order] PRIMARY KEY CLUSTERED
(
[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
/****** Object: Table [dbo].[OrderItem] Script Date: 6/9/2016 2:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[OrderItem](
[Id] [int] IDENTITY(1,1) NOT NULL,
[OrderId] [int] NOT NULL,
[OrderItemName] [varchar](100) NOT NULL,
[Qty] [int] NOT NULL,
CONSTRAINT [PK_OrderItem] PRIMARY KEY CLUSTERED
(
[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
ALTER TABLE [dbo].[OrderItem] WITH CHECK ADD CONSTRAINT [FK_OrderItem_Order] FOREIGN KEY([OrderId])
REFERENCES [dbo].[Order] ([Id])
GO
ALTER TABLE [dbo].[OrderItem] CHECK CONSTRAINT [FK_OrderItem_Order]
GO
Here is my LINQ statement
List<Order> olist = (from a in Orders where a.Id == 2 select a).ToList();
List<int> olistidlist = olist.Select (o => o.Id).ToList();
List<OrderItem> oilist = (from a in OrderItems where olistidlist.Contains(a.Id) select a).ToList();
//see results before
olist.Dump();
OrderItems.DeleteAllOnSubmit(oilist);
Orders.DeleteAllOnSubmit(olist);
//save changes
SubmitChanges();
//see results after
olist.Dump();
You are deleting OrderItems of which the OrderItem.Id is equal to values in olistidlist (only 2, presently). Of course, this must be OrderItem.OrderId.
By the way, an easier way to delete parent and child items generally is:
foreach (var order in Orders.Where(...))
{
OrderItems.DeleteAllOnSubmit(order.OrderItems);
Orders.DeleteOnSubmit(order);
}
So you don't have to move around with Id values.
Please find all the necessary scripts at the bottom of this post to create the scenario I'm describing here.
Scenario:
I have a "Transactions" table where I store all transactions in a stock market management app. ALL transactions are in there with the pertinent info e.g. TransactionType, TransactionAmount, etc.
The next two tables are super simple and self explanatory i.e. People and Companies.
I then have a table called TransactionsForCompanies where I store all transactions created by corporate customers. In this table, I have only two columns: TransactionId -- coming from the Transactions table -- CompanyId -- coming from the Companies table.
The next table called TransactionsForPeople is almost identical the last one but it's used for identifying transactions created by individuals.
Please see the DB structure and I think it'll make sense fairly easily.
Here's what I'm trying to do and where I need help.
I want to create a view that gives me the "Last Transaction Date" for people. So if a person had multiple transactions in the last month, this view is supposed to give me the last transaction date for that individual who might have had the transaction only 2 hours ago. Of course, the view will return last transaction date for ALL "individual customers".
To do this, I used the MAX function and the view worked nicely. However, because I'm using the MAX function, I cannot create an index for the view. As a result, I have a performance issue because my "Transactions" table has millions of records.
Of course the idea is to use the view in another SELECT statement so that I can generate nice reports about most and least active clients. This SELECT statement runs very slowly and when I look at the execution plan, the bottleneck is where I have my JOIN to the view that is using the MAX function.
QUESTION: How do I capture the last TransactionDate for people who had transactions in a way that gives me good performance?
Thanks...
USE [TestDb]
GO
/****** Object: Table [dbo].[Companies] Script Date: 4/7/2013 1:48:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Companies](
[CompanyId] [int] IDENTITY(1,1) NOT NULL,
[CompanyName] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Companies] PRIMARY KEY CLUSTERED
(
[CompanyId] 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
/****** Object: Table [dbo].[People] Script Date: 4/7/2013 1:48:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[People](
[PersonId] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](20) NOT NULL,
[MiddleName] [nvarchar](20) NULL,
[LastName] [nvarchar](20) NOT NULL,
CONSTRAINT [PK_People] PRIMARY KEY CLUSTERED
(
[PersonId] 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
/****** Object: Table [dbo].[Transactions] Script Date: 4/7/2013 1:48:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Transactions](
[TransactionId] [int] IDENTITY(1,1) NOT NULL,
[TransactionType] [nvarchar](50) NOT NULL,
[TransactionTimeStamp] [datetime] NOT NULL,
[TransactionAmount] [money] NOT NULL,
[Comments] [nvarchar](50) NULL,
CONSTRAINT [PK_Transactions] PRIMARY KEY CLUSTERED
(
[TransactionId] 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
/****** Object: Table [dbo].[TransactionsForCompanies] Script Date: 4/7/2013 1:48:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TransactionsForCompanies](
[TransactionId] [int] NOT NULL,
[CompanyId] [int] NOT NULL,
CONSTRAINT [PK_TransactionsForCompanies] PRIMARY KEY CLUSTERED
(
[TransactionId] ASC,
[CompanyId] 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
/****** Object: Table [dbo].[TransactionsForPeople] Script Date: 4/7/2013 1:48:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TransactionsForPeople](
[TransactionId] [int] NOT NULL,
[PersonId] [int] NOT NULL,
CONSTRAINT [PK_TransactionsForPeople] PRIMARY KEY CLUSTERED
(
[TransactionId] ASC,
[PersonId] 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 IDENTITY_INSERT [dbo].[Companies] ON
GO
INSERT [dbo].[Companies] ([CompanyId], [CompanyName]) VALUES (1, N'Company A')
GO
INSERT [dbo].[Companies] ([CompanyId], [CompanyName]) VALUES (2, N'Company B')
GO
INSERT [dbo].[Companies] ([CompanyId], [CompanyName]) VALUES (3, N'Company C')
GO
SET IDENTITY_INSERT [dbo].[Companies] OFF
GO
SET IDENTITY_INSERT [dbo].[People] ON
GO
INSERT [dbo].[People] ([PersonId], [FirstName], [MiddleName], [LastName]) VALUES (1, N'John', NULL, N'Doe')
GO
INSERT [dbo].[People] ([PersonId], [FirstName], [MiddleName], [LastName]) VALUES (2, N'Jane', NULL, N'Smith')
GO
INSERT [dbo].[People] ([PersonId], [FirstName], [MiddleName], [LastName]) VALUES (3, N'Betsy', NULL, N'Green')
GO
SET IDENTITY_INSERT [dbo].[People] OFF
GO
SET IDENTITY_INSERT [dbo].[Transactions] ON
GO
INSERT [dbo].[Transactions] ([TransactionId], [TransactionType], [TransactionTimeStamp], [TransactionAmount], [Comments]) VALUES (1, N'BUY', CAST(0x0000A1990122F5C4 AS DateTime), 300.0000, N'Got it!')
GO
INSERT [dbo].[Transactions] ([TransactionId], [TransactionType], [TransactionTimeStamp], [TransactionAmount], [Comments]) VALUES (2, N'BID', CAST(0x0000A19901236069 AS DateTime), 1753.5000, N'My best offer...')
GO
INSERT [dbo].[Transactions] ([TransactionId], [TransactionType], [TransactionTimeStamp], [TransactionAmount], [Comments]) VALUES (3, N'SELL', CAST(0x0000A19901236AF5 AS DateTime), 1753.5000, N'Will take it!')
GO
INSERT [dbo].[Transactions] ([TransactionId], [TransactionType], [TransactionTimeStamp], [TransactionAmount], [Comments]) VALUES (4, N'BUY', CAST(0x0000A19901236C21 AS DateTime), 1753.5000, N'Finalize purchase.')
GO
SET IDENTITY_INSERT [dbo].[Transactions] OFF
GO
INSERT [dbo].[TransactionsForCompanies] ([TransactionId], [CompanyId]) VALUES (3, 1)
GO
INSERT [dbo].[TransactionsForPeople] ([TransactionId], [PersonId]) VALUES (1, 2)
GO
INSERT [dbo].[TransactionsForPeople] ([TransactionId], [PersonId]) VALUES (2, 3)
GO
INSERT [dbo].[TransactionsForPeople] ([TransactionId], [PersonId]) VALUES (4, 3)
GO
ALTER TABLE [dbo].[Transactions] ADD CONSTRAINT [DF_Transactions_TransactionTimeStamp] DEFAULT (getutcdate()) FOR [TransactionTimeStamp]
GO
ALTER TABLE [dbo].[TransactionsForCompanies] WITH CHECK ADD CONSTRAINT [FK_TransactionsForCompanies_Companies] FOREIGN KEY([CompanyId])
REFERENCES [dbo].[Companies] ([CompanyId])
GO
ALTER TABLE [dbo].[TransactionsForCompanies] CHECK CONSTRAINT [FK_TransactionsForCompanies_Companies]
GO
ALTER TABLE [dbo].[TransactionsForCompanies] WITH CHECK ADD CONSTRAINT [FK_TransactionsForCompanies_Transactions] FOREIGN KEY([TransactionId])
REFERENCES [dbo].[Transactions] ([TransactionId])
GO
ALTER TABLE [dbo].[TransactionsForCompanies] CHECK CONSTRAINT [FK_TransactionsForCompanies_Transactions]
GO
ALTER TABLE [dbo].[TransactionsForPeople] WITH CHECK ADD CONSTRAINT [FK_TransactionsForPeople_People] FOREIGN KEY([PersonId])
REFERENCES [dbo].[People] ([PersonId])
GO
ALTER TABLE [dbo].[TransactionsForPeople] CHECK CONSTRAINT [FK_TransactionsForPeople_People]
GO
ALTER TABLE [dbo].[TransactionsForPeople] WITH CHECK ADD CONSTRAINT [FK_TransactionsForPeople_Transactions] FOREIGN KEY([TransactionId])
REFERENCES [dbo].[Transactions] ([TransactionId])
GO
ALTER TABLE [dbo].[TransactionsForPeople] CHECK CONSTRAINT [FK_TransactionsForPeople_Transactions]
GO
Your not going to be able to create an indexed view if you want to use max(), as you have said.
How about either:
(i) Changing the primary key to be nonclustered, and then adding a clustered index on TransactionTimestamp for the Transactions table?
(ii) Adding an index on TransactionId, TransactionTimestamp on the Transactions table.
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
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
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.