Trigger is not inserting some columns value - sql-server

I am working in two table. one is AspNetUser and second is App_User so I am adding any records in aspnetuser then one trigger will be fire and it will add that same data in app_usr table.
But in my case there is one issue all other values of records is inserting in app_user table but there is 2 values is not inserting in new table
AspNetUser Table schema:
CREATE TABLE [dbo].[AspNetUsers](
[Id] [nvarchar](128) NOT NULL,
[Email] [nvarchar](256) NULL,
[UserName] [nvarchar](256) NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[MiddleInitial] [nvarchar](1) NULL,
[LastName] [nvarchar](50) NOT NULL,
[AccountID] [int] NOT NULL,
[SystemLevel] [int] NOT NULL,
[CreatedBy] [int] NULL,
[active] [bit] NOT NULL,
[VendorAccountID] [int] NOT NULL,
[VendorUser] [bit] NOT NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Please see below is App_User's schema:
CREATE TABLE [dbo].[App_User](
[ID] [int] IDENTITY(1000,1) NOT NULL,
[account_id] [int] NOT NULL,
[system_level] [int] NOT NULL,
[logon] [char](256) NOT NULL,
[first_name] [char](50) NULL,
[middle_initial] [char](1) NULL,
[last_name] [char](50) NULL,
[email] [char](256) NULL,
[description] [char](250) NULL,
[created_by] [int] NOT NULL,
[creation_date] [datetime] NULL,
[modified_by] [int] NULL,
[modification_date] [datetime] NULL,
[active] [bit] NOT NULL,
[default_approver] [bit] NULL,
[vendor_account_id] [int] NULL,
[vendor_user] [bit] NOT NULL,
PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
GO
Please verify I have inserted below trigger's code:
CREATE TRIGGER [dbo].[Tr_aspnet_Users_CreateUser] ON [dbo].[AspNetUsers]
AFTER INSERT
AS
DECLARE #AccountID int
DECLARE #VendorAccountID int
DECLARE #VendorUser bit
DECLARE #SystemLevel int
DECLARE #UserName varchar(256)
DECLARE #FirstName varchar(50)
DECLARE #MiddleInitial varchar(1)
DECLARE #LastName varchar(50)
DECLARE #Email varchar(256)
DECLARE #CreatedBy int
SELECT #AccountID = i.AccountID from inserted i;
SELECT #VendorAccountID = i.VendorAccountID from inserted i;
SELECT #VendorUser = i.VendorUser from inserted i;
SELECT #SystemLevel = i.SystemLevel from inserted i;
SELECT #UserName = i.UserName from inserted i;
SELECT #FirstName = i.FirstName from inserted i;
SELECT #MiddleInitial = i.MiddleInitial from inserted i;
SELECT #LastName = i.LastName from inserted i;
SELECT #Email = i.Email from inserted i;
SELECT #CreatedBy = i.CreatedBy from inserted i;
IF(#VendorAccountID=0)
SET #VendorAccountID=NULL
BEGIN
SET NOCOUNT ON;
INSERT INTO [dbo].[App_User]
([active]
,[account_id]
,[system_level]
,[logon]
,[first_name]
,[middle_initial]
,[last_name]
,[email]
,[vendor_account_id]
,[vendor_user]
,[created_by]
,[creation_date])
VALUES
(1
,#AccountID
,#SystemLevel
,#UserName
,#FirstName
,#MiddleInitial
,#LastName
,#Email
,#VendorAccountID
,#VendorUser
,#CreatedBy
,GETDATE())
END
GO
Now Issue is that while trigger fires then all other value is inserting properly but vendor_account_id and vendor_user is not inserting.
Can anyone please help what should be issue here.

Related

Identity Db : Duplicate email error even if constraint not set on the column

I am getting an exception of duplicate email in the identitydb while creating a user from my asp.net api.
The strange thing is that there is no constraint set on the email column or normalised email column so not
sure why it is not allowing me to enter same email address. Is there some default setting in the identity db for checking email dulication
Error
Code : "DuplicateEmail"
Description : "Email 'test#test.com' is already taken."
Execption caught while tracing in the profiler
exec sp_executesql N'EXEC GlobalExceptionInsert #DateTimeStamp, #Thread, #Class, #Method, #UserName, #Message, #Exception',N'#DateTimeStamp nvarchar(23),#Thread nvarchar(2),#Class nvarchar(13),#Method nvarchar(8),#UserName nvarchar(17),#Message nvarchar(115),#Exception nvarchar(163)',#DateTimeStamp=N'2019/10/23 14:26:13.078',#Thread=N'15',#Class=N'<AddUser>d__7',#Method=N'MoveNext',#UserName=N'Argentex.Core.Api',#Message=N'Error creating new user tmenon. Message: Code: DuplicateEmail. Description: Email ''test#test.com'' is already taken.',#Exception=N'Argentex.Core.Api.Exceptions.IdentityException: Error creating new user tmenon. Message: Code: DuplicateEmail. Description: Email ''test#test.com'' is already taken.'
Here is the screenshot of the table
Table
Constraint
Table definition
USE [IdentityDB_CSR]
GO
/****** Object: Table [dbo].[User] Script Date: 23/10/2019 13:28:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[User](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](256) NULL,
[NormalizedUserName] [nvarchar](256) NULL,
[Email] [nvarchar](256) NULL,
[NormalizedEmail] [nvarchar](256) NULL,
[EmailConfirmed] [bit] NOT NULL,
[PasswordHash] [nvarchar](max) NULL,
[SecurityStamp] [nvarchar](max) NULL,
[ConcurrencyStamp] [nvarchar](max) NULL,
[PhoneNumber] [nvarchar](max) NULL,
[PhoneNumberConfirmed] [bit] NOT NULL,
[TwoFactorEnabled] [bit] NOT NULL,
[LockoutEnd] [datetimeoffset](7) NULL,
[LockoutEnabled] [bit] NOT NULL,
[AccessFailedCount] [int] NOT NULL,
[AuthUserId] [int] NOT NULL,
[Title] [nvarchar](16) NOT NULL,
[Forename] [nvarchar](256) NOT NULL,
[Surname] [nvarchar](100) NOT NULL,
[ClientCompanyId] [int] NOT NULL,
[ClientCompanyContactId] [int] NOT NULL,
[UpdatedByAuthUserId] [int] NOT NULL,
[PhoneNumberMobile] [nvarchar](128) NULL,
[PhoneNumberOther] [nvarchar](128) NULL,
[LastUpdate] [datetime2](7) NULL,
[ASPNumber] [nvarchar](max) NULL,
[ASPCreationDate] [datetime2](7) NULL,
[LastTelephoneChange] [datetime2](7) NULL,
[LastEmailChange] [datetime2](7) NULL,
[LastPasswordChange] [datetime2](7) NOT NULL,
[CreateDate] [datetime2](7) NOT NULL,
[IsApproved] [bit] NOT NULL,
[Birthday] [datetime2](7) NULL,
[Notes] [nvarchar](max) NULL,
[Position] [nvarchar](50) NULL,
[PrimaryContact] [bit] NULL,
[IsDeleted] [bit] NOT NULL,
[IsAdmin] [bit] NOT NULL,
[ApprovedByAuthUserId] [int] NULL,
[IsAuthorisedSignatory] [bit] NOT NULL,
[IsSignatory] [bit] NOT NULL,
CONSTRAINT [PK_User] 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],
CONSTRAINT [AK_User_AuthUserId] UNIQUE NONCLUSTERED
(
[AuthUserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[User] ADD DEFAULT (getdate()) FOR [LastPasswordChange]
GO
ALTER TABLE [dbo].[User] ADD DEFAULT (getdate()) FOR [CreateDate]
GO
ALTER TABLE [dbo].[User] ADD DEFAULT ((0)) FOR [IsAuthorisedSignatory]
GO
ALTER TABLE [dbo].[User] ADD DEFAULT ((0)) FOR [IsSignatory]
GO
Definition for UserNameIndex
USE [IdentityDB_CSR]
GO
SET ANSI_PADDING ON
GO
/****** Object: Index [UserNameIndex] Script Date: 23/10/2019 13:58:00 ******/
CREATE UNIQUE NONCLUSTERED INDEX [UserNameIndex] ON [dbo].[User]
(
[NormalizedUserName] ASC
)
WHERE ([NormalizedUserName] IS NOT NULL)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
When creating user with ASP.NET Core Identity , it will raise the default UserValidator library which will make sure email is not empty, valid, and unique if options.User.RequireUniqueEmail of IdentityOptions is true :
if (manager.Options.User.RequireUniqueEmail)
{
await ValidateEmail(manager, user, errors);
}
ValidateEmail :
// make sure email is not empty, valid, and unique
private async Task ValidateEmail(UserManager<TUser> manager, TUser user, List<IdentityError> errors)
{
var email = await manager.GetEmailAsync(user);
if (string.IsNullOrWhiteSpace(email))
{
errors.Add(Describer.InvalidEmail(email));
return;
}
if (!new EmailAddressAttribute().IsValid(email))
{
errors.Add(Describer.InvalidEmail(email));
return;
}
var owner = await manager.FindByEmailAsync(email);
if (owner != null &&
!string.Equals(await manager.GetUserIdAsync(owner), await manager.GetUserIdAsync(user)))
{
errors.Add(Describer.DuplicateEmail(email));
}
}
Source code
You can set the options in ConfigureServices:
services.Configure<IdentityOptions>(options =>
{
options.User.RequireUniqueEmail = false;
...
});

Msg 8152 String or binary data would be truncated

I know this has been asked before, but none of the answers are fixing the issue, need another set of eyes. I'm trying to create a table and seed it with some values. I don't have any value constraints so I'm not sure why I'm getting the error I'm getting.
CREATE TABLE [dbo].[AvailableTime]
(
[Id] [INT] IDENTITY(1,1) NOT NULL,
[TimeString] [NCHAR] NOT NULL,
[TimeValue] [NCHAR] NOT NULL,
[CompanyId] [INT] NOT NULL,
[CompanyName] [NVARCHAR](MAX) NULL,
[LocationId] [INT] NOT NULL,
[LocationName] [NVARCHAR] NOT NULL,
[IsClaimed] [BIT] NOT NULL,
CONSTRAINT [PK_AvailableTime]
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] TEXTIMAGE_ON [PRIMARY]
GO
INSERT INTO dbo.AvailableTime (TimeString, TimeValue, CompanyId, CompanyName,
LocationId, LocationName, IsClaimed)
VALUES ('2019-01-07T00:00:00', '12:00 AM', 1, 'Company',
2, 'Inver Grove', 'FALSE');
You should never specify a CHAR, VARCHAR, NCHAR or NVARCHAR column (or variable, or parameter) without specifying an explicit length!
If you omit the specific length, in some cases you'll end up with variable or column of exactly ONE character of length! That's typically NOT what you want!
ALSO: why are you storing TimeString and TimeValue as NCHAR?? Doesn't make any sense - use the most appropriate datatype - and here, that would be DATETIME2(n) and TIME.
So define your table like this:
CREATE TABLE [dbo].[AvailableTime]
(
[Id] [INT] IDENTITY(1,1) NOT NULL,
[TimeString] DATETIM2(0) NOT NULL,
[TimeValue] TIME(0) NOT NULL,
[CompanyId] [INT] NOT NULL,
[CompanyName] [NVARCHAR](MAX) NULL,
[LocationId] [INT] NOT NULL,
[LocationName] [NVARCHAR](100) NOT NULL,
[IsClaimed] [BIT] NOT NULL,
and you should be fine.
You need declare the size of your CHAR & VARCHAR fields in the table:
CREATE TABLE [dbo].[AvailableTime]
(
[Id] [INT] IDENTITY(1,1) NOT NULL,
[TimeString] [NCHAR](50) NOT NULL,
[TimeValue] [NCHAR](50) NOT NULL,
[CompanyId] [INT] NOT NULL,
[CompanyName] [NVARCHAR](MAX) NULL,
[LocationId] [INT] NOT NULL,
[LocationName] [NVARCHAR](50) NOT NULL,
[IsClaimed] [BIT] NOT NULL,
CONSTRAINT [PK_AvailableTime]
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] TEXTIMAGE_ON [PRIMARY]
GO
You have a error in insert query, mismatch types in last column.
INSERT INTO dbo.AvailableTime (TimeString, TimeValue, CompanyId, CompanyName,
LocationId, LocationName, IsClaimed)
VALUES ('2019-01-07T00:00:00', '12:00 AM', 1, 'Company', 2, 'Inver Grove', 0);

Stored procedure not executing the update part until run a second time

I have a stored procedure that, when ran, does an initial insert into a a table from a view, followed by an update statement that modifies a table in the view the first select statement uses (code is below):
ALTER PROCEDURE [dbo].[LFC_sp_LIT_PgmrRequestForm]
AS
BEGIN
SET NOCOUNT ON;
insert into firebird.helpdesk.dbo.tbl_program_request (Requester, Description, Priority, DateRequest, project_status, department, category, requester_email, DueDate, Note)
select dept_name, submitter_first_name + '-' + issue_description, severity_level, getdate(), 'Not Started', dept_name, issue_category, submitter_email, date_due, issue_details
from ics_net..CUS_CF_PGMR_REQUEST_View
where finalbalance = 0;
UPDATE ics_net..CF_Submission
SET finalbalance = 5
WHERE finalbalance = 0
AND FormId = '79A807D9-230B-494C-A609-A284DBBE41B8';
END
This procedure is called whenever a web form is submitted, and the goal is to move the data from the web form database into our help desk database. The web form has a final balance field in the database, that is set to zero. When it is moved, we update it to a non-zero number.
What happens is that the first statement executes, but the second update never happens. Once this is called again, the first statement executes, and the second one works for the statement that was supposed to be previously updated. Things I've tried to resolve the issue are:
Use the ROWLOCK hint for both statements
I've made sure the transaction isolation level is READ COMMITTED
I can't think of anything else to do, other than to use the NOLOCK hint on the select statement, but I'm very hesitant to do that. Any ideas? Thanks.
EDIT 1) Based on some discussion, I want to clarify a couple things:
There aren't any existing triggers on any of the tables
underlying this query.
The initial select is based on a view, while the second update
references a table that makes up the view.
Edit 2) Some more details
The view definition:
ALTER VIEW [dbo].[CUS_CF_PGMR_REQUEST_View] AS
select s.SubmissionId,
s.FormId,
s.SubmittedDate,
s.UserId,
s.Status,
sfn.AnswerValue as [submitter_first_name],
sub_email.AnswerValue as [submitter_email],
dname.AnswerValue as [dept_name],
d_due.AnswerValue as [date_due],
i_cat.AnswerValue as [issue_category],
sec_lev.AnswerValue as [severity_level],
i_desc.AnswerValue as [issue_description],
i_det.AnswerValue as [issue_details],
s.FinalBalance
from CF_Submissions s
left outer join CF_Answers sfn on sfn.ItemID = 'df5307ca-d9a8-4c74-955e-7fe80caafdc0'
and sfn.SubmissionID=s.SubmissionID
left outer join CF_Answers sub_email on sub_email.ItemID = '27e8e2fd-13f8-4c5a-a6bb-bc68fa7d4af5'
and sub_email.SubmissionID=s.SubmissionID
left outer join CF_Answers dname on dname.ItemID = '2826ee1b-759e-4325-b0ba-32a86ed7f07a'
and dname.SubmissionID=s.SubmissionID
left outer join CF_Answers d_due on d_due.ItemID = '5e087866-63ce-41f1-bb32-443770fdf388'
and d_due.SubmissionID=s.SubmissionID
left outer join CF_Answers i_cat on i_cat.ItemID = '32be52b1-1539-4d9b-9f7c-ffb370188396'
and i_cat.SubmissionID=s.SubmissionID
left outer join CF_Answers sec_lev on sec_lev.ItemID = 'f795ff66-342b-4155-86d6-7655dc2b10a5'
and sec_lev.SubmissionID=s.SubmissionID
left outer join CF_Answers i_desc on i_desc.ItemID = '3ff0e614-bdf6-4710-9ba0-6f7356c67032'
and i_desc.SubmissionID=s.SubmissionID
left outer join CF_Answers i_det on i_det.ItemID = 'dd5b797d-a407-4bc7-a73c-daacb3abe660'
and i_det.SubmissionID=s.SubmissionID
where s.FormId = '79a807d9-230b-494c-a609-a284dbbe41b8'
Table Definitions Underlying The View
CREATE TABLE [dbo].[CF_Answers](
[AnswerID] [uniqueidentifier] NOT NULL,
[SubmissionID] [uniqueidentifier] NULL,
[ItemID] [uniqueidentifier] NULL,
[AnswerValue] [varchar](max) NULL,
[MItemID] [uniqueidentifier] NULL,
[RowIndex] [int] NULL,
[ChildItemID] [uniqueidentifier] NULL,
[DisplayText] [varchar](max) NULL,
[NumericValue] [numeric](8, 2) NULL,
[IsVisibleOnSubmit] [bit] NULL,
CONSTRAINT [PK_CF_Answers] PRIMARY KEY CLUSTERED
(
[AnswerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[CF_Submissions](
[SubmissionID] [uniqueidentifier] NOT NULL,
[UserID] [uniqueidentifier] NULL,
[FormID] [uniqueidentifier] NULL,
[SubmittedDate] [datetime] NULL,
[FinalBalance] [decimal](18, 2) NULL,
[WorkflowID] [uniqueidentifier] NULL,
[Status] [int] NULL,
[TransactionID] [varchar](50) NULL,
[WaiverCode] [varchar](max) NULL,
CONSTRAINT [PK_CF_Submissions] PRIMARY KEY CLUSTERED
(
[SubmissionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
The definition of the destination table for the insert:
CREATE TABLE [dbo].[tbl_program_request](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Requester] [nvarchar](50) NULL,
[Description] [nvarchar](255) NULL,
[Priority] [nvarchar](10) NULL,
[DateRequest] [datetime] NULL,
[WorkingOn] [nvarchar](30) NULL,
[CompletedDate] [datetime] NULL,
[StartDate] [nvarchar](15) NULL,
[Note] [nvarchar](max) NULL,
[project_status] [nvarchar](25) NULL,
[hours_week] [decimal](4, 2) NULL,
[hours_total] [decimal](10, 2) NULL,
[department] [nvarchar](30) NULL,
[category] [nvarchar](20) NULL,
[requester_email] [nvarchar](30) NULL,
[DueDate] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Finally, some sample data that was pulled from the view:
SubmissionId - B81CE5F8-A87B-42B1-9339-2B36166394AB
FormId - 79A807D9-230B-494C-A609-A284DBBE41B8
SubmittedDate - 1/24/2018 16:43
UserId - 58E3958A-A786-4CB9-8EDE-0837ACE187BD
Status - 1
submitter_first_name - SM
submitter_email - email#organization
dept_name - LIT
date_due - 1/28/2018
issue_category -MISC
severity_level - LOW
issue_description - test3
issue_details - test3
FinalBalance - 0
Just to clarify, at the end of the SP, FinalBalance should equal 5. However, it isn't set to 5 until the second time it's ran, causing a double insert into the tbl_program_request table.

SQL Server DELETE performance issues

I have a table with approximately 1 million rows. Part of our maintenance involves deleting old row each day, but this is taking about 40 minutes.
The delete statement is:
DELETE
FROM [dbGlobalPricingMatrix].[dbo].[tblPricing]
WHERE type = 'car'
AND capid NOT IN
(SELECT cder_id FROM PUB_CAR.dbo.CapDer WHERE cder_discontinued
IS NULL OR DATEDIFF(dd,cder_discontinued,GETDATE()) <= 7)
AND source = #source
Is there anything I can do to improve the performance?
Thanks
As Requested:
CREATE TABLE [dbo].[tblPricing](
[id] [int] IDENTITY(1,1) NOT NULL,
[type] [varchar](50) NULL,
[capid] [int] NULL,
[source] [varchar](50) NULL,
[product] [varchar](50) NULL,
[term] [int] NULL,
[milespa] [int] NULL,
[maintained] [bit] NULL,
[price] [money] NULL,
[created] [datetime] NULL,
[updated] [datetime] NULL,
[notes] [varchar](1000) NULL,
[painttype] [char](1) NULL,
[activeflag] [bit] NULL,
[DealerId] [int] NULL,
[FunderId] [int] NULL,
[IsSpecial] [bit] NULL,
[username] [varchar](50) NULL,
[expiry] [datetime] NULL,
CONSTRAINT [PK_tblPricing] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[CAPDer](
[cder_ID] [int] NOT NULL,
[cder_capcode] [char](20) NULL,
[cder_mancode] [int] NULL,
[cder_rancode] [int] NULL,
[cder_modcode] [int] NULL,
[cder_trimcode] [int] NULL,
[cder_name] [varchar](50) NULL,
[cder_introduced] [datetime] NULL,
[cder_discontinued] [datetime] NULL,
[cder_orderno] [int] NULL,
[cder_vehiclesector] [tinyint] NULL,
[cder_doors] [tinyint] NULL,
[cder_drivetrain] [char](1) NULL,
[cder_fueldelivery] [char](1) NULL,
[cder_transmission] [char](1) NULL,
[cder_fueltype] [char](1) NULL,
CONSTRAINT [PK_CapDer] PRIMARY KEY CLUSTERED
(
[cder_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
Okay, as I suspected, you do not seem to have indexes for the fields that you reference in your DELETE query. So, add indexes for type, capid, cder_discontinued, and source.
Additionally, you might want to try AND capid IN (SELECT cder_id FROM PUB_CAR.dbo.CapDer WHERE cder_discontinued IS NOT NULL AND DATEDIFF(dd,cder_discontinued,GETDATE()) > 7). The optimizer of MS-SQL-Server should actually be doing this for you, but you never know, it is worth trying.

Delete Query: 14 minute to no response

I have a Sql Azure database, everything was good from last 6 months until today, when a simple
Delete from ListData where ListID=2323
fail to delete 7500 records out of 1.9 Million records after 14 minutes of running query. However Select query take less than 2-3 second to list them all.
Previously the delete works much like select and it usually take less than 20 second to finish delete operation. something is wrong today only.
Complete database size is 1.1GB where as we have Web edition set at 5GB so, we have plenty of space available.
Any idea what is going wrong? that delete has cause some serious problem in system which cause my client lose quite a money.
Thanks for any guide.
Edit: I do have couple of Index on table, but no trigger, FK or any other such thing in table. LISTID is foreign key [logically], and RecordID [another column in table] is auto increment id in Listdata table.
*Edit 2 *:
/****** Object: Table [dbo].[tblSalesListData] Script Date: 02-07-2013 11:45:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ListData](
[RecordID] [bigint] IDENTITY(1,1) NOT NULL,
[ListID] [bigint] NULL,
[SalesID] [bigint] NULL,
[UserID] [varchar](100) NULL,
[FirstName] [varchar](100) NULL,
[MiddleName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[Address1] [varchar](100) NULL,
[Address2] [varchar](100) NULL,
[City] [varchar](100) NULL,
[State] [varchar](100) NULL,
[ZipCode] [varchar](10) NULL,
[WorkPhone] [varchar](15) NULL,
[HomePhone] [varchar](15) NULL,
[CellPhone] [varchar](15) NULL,
[Email] [varchar](100) NULL,
[DealerCode] [varchar](20) NULL,
[IsPrinted] [varchar](10) NULL,
[tag] [varchar](100) NULL,
[RecordDate] [datetime] NULL,
[CustomInfo] [text] NULL,
[SourceData] [text] NULL,
CONSTRAINT [PK_ListData] PRIMARY KEY CLUSTERED
(
[RecordID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[ListData] ADD DEFAULT ('N') FOR [IsPrinted]
GO
Try to add index and change table structure -
CREATE TABLE dbo.tblSalesListData
(
RecordID BIGINT IDENTITY(1,1) NOT NULL PRIMARY KEY,
ListID BIGINT NOT NULL, -- NULL --> NOT NULL
SalesID BIGINT NULL,
UserID VARCHAR(100) NULL,
FirstName VARCHAR(100) NULL,
MiddleName VARCHAR(50) NULL,
LastName VARCHAR(50) NULL,
Address1 VARCHAR(100) NULL,
Address2 VARCHAR(100) NULL,
City VARCHAR(100) NULL,
[State] VARCHAR(100) NULL,
ZipCode VARCHAR(10) NULL,
WorkPhone VARCHAR(15) NULL,
HomePhone VARCHAR(15) NULL,
CellPhone VARCHAR(15) NULL,
Email VARCHAR(100) NULL,
DealerCode VARCHAR(20) NULL,
IsPrinted VARCHAR(10) NULL,
tag VARCHAR(100) NULL,
RecordDate DATETIME NULL,
CustomInfo VARCHAR(MAX) NULL, -- TEXT --> VARCHAR(MAX)
SourceData VARCHAR(MAX) NULL -- TEXT --> VARCHAR(MAX)
)
GO
CREATE /*UNIQUE*/ NONCLUSTERED INDEX IX_ListID ON dbo.tblSalesListData
(
ListID ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
I have a little bit of same problem. I did the following step. but be sure to back up the database before doing these steps.
Create another table with identical structure
Insert the data in new table of the old table
Drop the old table
and try again to see how much time will it take.
Thanks for #Dinup and #Devart that give me idea, though I didn't fully follow their word, but both of them guide me in direction where I found solution as :
Delete all Indexes based on my ListID.
Run my Query, it take less than 1 second now.
Recreate my indexes.
Happy Living.

Resources