stored procedure inserting values in wrong columns - sql-server

I am facing a strange problem,
My c# program is inserting values into database(basically checks if the record exists then updates it, otherwise, inserts into the table)
the query for the stored procedure as well as table is shown below:
Table
CREATE TABLE [dbo].[PurchaseReceiptbySheetOil](
[id] [int] IDENTITY(1,1) NOT NULL,
[LPOId] [int] NULL,
[POLineNumber] [nvarchar](100) NULL,
[Serial] [nvarchar](100) NULL,
[DateLoaded] [date] NULL,
[truck] [nvarchar](100) NULL,
[Trailer] [nvarchar](100) NULL,
[Transporter] [nvarchar](100) NULL,
[Driver] [nvarchar](max) NULL,
[PassportNumber] [nvarchar](100) NULL,
[ObserverdVolume] [nvarchar](100) NULL,
[Terminal] [nvarchar](100) NULL,
[Tank] [nvarchar](100) NULL,
[TempInTank] [nvarchar](100) NULL,
[VCF20] [float] NULL,
[VolumeLTS20C] [float] NULL,
[Density20C] [float] NULL,
[WeightMTons] [float] NULL,
[Destination] [nvarchar](max) NULL,
[BottomSEALNRS] [nvarchar](max) NULL,
[TopSealNRS] [nvarchar](100) NULL,
[SAMPLESEALNRS] [nvarchar](max) NULL,
[PhysicalDipsOnTheTruckinMM1] [int] NULL,
[PhysicalDipsOnTheTruckinMM2] [int] NULL,
[PhysicalDipsOnTheTruckinMM3] [int] NULL,
[PhysicalDipsOnTheTruckinMM4] [int] NULL,
[PhysicalDipsOnTheTruckinMM5] [int] NULL,
[PhysicalDipsOnTheTruckinMM6] [int] NULL,
[Site] [nvarchar](100) NULL,
[LineNumber] [int] NULL,
[CreatedOn] [datetime] NULL,
[UpdatedOn] [datetime] NULL,
[CreatedBy] [nvarchar](100) NULL,
[UpdatedBy] [nvarchar](100) NULL
)
Stored Procedure
CREATE PROCEDURE [dbo].[CreateUpdatePurchaseReceiptbySheetOil]
#Site nvarchar(100),
#CreatedOn datetime,
#UpdatedOn datetime,
#CreatedBy nvarchar(100),
#UpdatedBy nVarchar(100),
#DateLoaded date,
#truck nvarchar(100),
#Trailer nvarchar(100),
#Transporter nvarchar(100),
#Driver nvarchar(max),
#PassportNumber nvarchar(100),
#ObserverdVolume nvarchar(100),
#Terminal nvarchar(100),
#Tank nvarchar(100),
#TempInTank nvarchar(100),
#VCF20 float,
#VolumeLTS20C float,
#Density20C float,
#WeightMTons float,
#Destination nvarchar(max),
#BottomSEALNRS nvarchar(max),
#SAMPLESEALNRS nvarchar(max),
#PhysicalDipsOnTheTruckinMM1 int,
#PhysicalDipsOnTheTruckinMM2 int,
#PhysicalDipsOnTheTruckinMM3 int,
#PhysicalDipsOnTheTruckinMM4 int,
#PhysicalDipsOnTheTruckinMM5 int,
#PhysicalDipsOnTheTruckinMM6 int,
#Serial Nvarchar(100),
#LineNumber int,
#POLineNumber int,
#TopSealNRS nvarchar(100),
#LPOId nvarchar(100)
AS
BEGIN
if exists(select * from [PurchaseReceiptbySheetOil] where Site= #Site and
Serial=#Serial and LineNumber = #LineNumber)
BEGIN
UPDATE [dbo].[PurchaseReceiptbySheetOil]
SET [DateLoaded] = #DateLoaded,
UpdatedOn =#UpdatedOn,
UpdatedBy=#UpdatedBy,
[truck] = #truck
,[Trailer] = #Trailer
,[Transporter] = #Transporter
,[Driver] = #Driver
,[PassportNumber] = #PassportNumber
,[ObserverdVolume] = #ObserverdVolume
,[Terminal] = #Terminal
,[Tank] = #Tank
,[TempInTank] = #TempInTank
,[VCF20] = #VCF20
,[VolumeLTS20C] = #VolumeLTS20C
,[Density20C] = #Density20C
,[WeightMTons] = #WeightMTons
,[Destination] = #Destination
,[BottomSEALNRS] = #BottomSEALNRS
,[SAMPLESEALNRS] = #SAMPLESEALNRS
,[PhysicalDipsOnTheTruckinMM1] = #PhysicalDipsOnTheTruckinMM1
,[PhysicalDipsOnTheTruckinMM2] = #PhysicalDipsOnTheTruckinMM2
,[PhysicalDipsOnTheTruckinMM3] = #PhysicalDipsOnTheTruckinMM3
,[PhysicalDipsOnTheTruckinMM4] = #PhysicalDipsOnTheTruckinMM4
,[PhysicalDipsOnTheTruckinMM5] = #PhysicalDipsOnTheTruckinMM5
,[PhysicalDipsOnTheTruckinMM6] = #PhysicalDipsOnTheTruckinMM6
,[Serial] = #Serial
,TopSealNRS=#TopSealNRS
,LPOId=#LPOId
WHERE Site= #Site and Serial=#Serial and LineNumber = #LineNumber
END
else
BEGIN
INSERT INTO [dbo].[PurchaseReceiptbySheetOil]
([LPOId]
,[POLineNumber]
,[Serial]
,[DateLoaded]
,[truck]
,[Trailer]
,[Transporter]
,[Driver]
,[PassportNumber]
,[ObserverdVolume]
,[Terminal]
,[Tank]
,[TempInTank]
,[VCF20]
,[VolumeLTS20C]
,[Density20C]
,[WeightMTons]
,[Destination]
,[BottomSEALNRS]
,[TopSealNRS]
,[SAMPLESEALNRS]
,[PhysicalDipsOnTheTruckinMM1]
,[PhysicalDipsOnTheTruckinMM2]
,[PhysicalDipsOnTheTruckinMM3]
,[PhysicalDipsOnTheTruckinMM4]
,[PhysicalDipsOnTheTruckinMM5]
,[PhysicalDipsOnTheTruckinMM6]
,[Site]
,[LineNumber]
,[CreatedOn]
,[UpdatedOn]
,[CreatedBy]
,[UpdatedBy])
VALUES
(#LPOId,#POLineNumber,
#Serial,#DateLoaded,
#truck,#Trailer,#Transporter,#Driver,
#PassportNumber,#ObserverdVolume,#Terminal,#Tank,#TempInTank,
#VCF20,#VolumeLTS20C,#Density20C,#WeightMTons,#Destination,#BottomSEALNRS,
#TopSealNRS,#SAMPLESEALNRS,
#PhysicalDipsOnTheTruckinMM1,#PhysicalDipsOnTheTruckinMM2,
#PhysicalDipsOnTheTruckinMM3,#PhysicalDipsOnTheTruckinMM4,
#PhysicalDipsOnTheTruckinMM5,#PhysicalDipsOnTheTruckinMM6,#Site,
#LineNumber,#CreatedOn,#UpdatedOn,#CreatedBy,#UpdatedBy)
END
END
Now when i run the following query to execute stored procedure:
exec sp_executesql N'EXECUTE [dbo].[CreateUpdatePurchaseReceiptbySheetOil]
#Site ,#CreatedOn ,
#UpdatedOn ,#CreatedBy
,#UpdatedBy ,#DateLoaded ,#truck
,#Trailer ,#Transporter ,#Driver
,#PassportNumber ,#ObserverdVolume
,#Terminal ,#Tank ,#TempInTank ,#VCF20
,#VolumeLTS20C ,#Density20C ,#WeightMTons
,#Destination ,#BottomSEALNRS,#TopSealNRS
,#SAMPLESEALNRS ,#PhysicalDipsOnTheTruckinMM1
,#PhysicalDipsOnTheTruckinMM2 ,#PhysicalDipsOnTheTruckinMM3
,#PhysicalDipsOnTheTruckinMM4 ,#PhysicalDipsOnTheTruckinMM5
,#PhysicalDipsOnTheTruckinMM6 ,#Serial ,#LineNumber
,#POLineNumber,#LPOId',N'#CreatedBy nvarchar(7),#CreatedOn datetime,
#UpdatedBY nvarchar(7),#UpdatedOn datetime,#Site nvarchar(7),
#DateLoaded nvarchar(9),#truck nvarchar(7),#Trailer nvarchar(7),
#Transporter nvarchar(5),#Driver nvarchar(8),#PassportNumber nvarchar(8),
#ObserverdVolume nvarchar(6),#Terminal nvarchar(5),#Tank
nvarchar(3),#TempInTank nvarchar(4),
#VCF20 nvarchar(6),#VolumeLTS20C nvarchar(6),#Density20C
nvarchar(6),#WeightMTons nvarchar(6),
#Destination nvarchar(5),#BottomSEALNRS nvarchar(14),#TopSealNRS
nvarchar(33),#SAMPLESEALNRS nvarchar(7),
#PhysicalDipsOnTheTruckinMM1 nvarchar(4),#PhysicalDipsOnTheTruckinMM2
nvarchar(4),#PhysicalDipsOnTheTruckinMM3 nvarchar(4),
#PhysicalDipsOnTheTruckinMM4 nvarchar(4),#PhysicalDipsOnTheTruckinMM5
nvarchar(4),#PhysicalDipsOnTheTruckinMM6 nvarchar(4),
#Serial nvarchar(5),#LineNumber int,#POLineNumber int,#LPOId int',
#CreatedBy=N'Tanveer',
#CreatedOn='2017-05-08 11:50:24.283',
#UpdatedBY=N'Tanveer',
#UpdatedOn='2017-05-08 11:50:24.283',
#Site=N'Site001',
#DateLoaded=N'20-Apr-17',
#truck='',
#Trailer='',
#Transporter=N'00002',
#Driver='',
#PassportNumber=''
#ObserverdVolume=N'40.000',
#Terminal=N'TOTAL',
#Tank=N'223',#TempInTank=N'30.0',#VCF20=N'0.9915',#VolumeLTS20C=N'39.660',
#Density20C=N'0.8219',
#WeightMTons=N'32.597',#Destination=N' DRC ',#BottomSEALNRS=N' 02697558/559
',#TopSealNRS=N' 02697560 TO 562+02697564 TO 566 ',
#SAMPLESEALNRS=N'781845 '
,#PhysicalDipsOnTheTruckinMM1=N'1472',#PhysicalDipsOnTheTruckinMM2=N'1592',
#PhysicalDipsOnTheTruckinMM3=N'1706',#PhysicalDipsOnTheTruckinMM4=N'1832',
#PhysicalDipsOnTheTruckinMM5=N'1808',
#PhysicalDipsOnTheTruckinMM6=N'1362',#Serial=N'00001',#LineNumber=8,
#POLineNumber=0,#LPOId=7
the values for the columns get swapped during the insert, Note the value for serial is 0001 but it will insert as 1362 instead of 0001 and for some other columns also the values will change(not all).
Please note that I have checked the sequence of columns in insert and
values sections. I am specifying columns but still facing this issue.
I have dropped and created the table again.
During debugging in sql
server, the value is correct when debugging starts i.e.0001 but then
changes, i don\t know why.

The sequence of parameters in Stored procedure definition should be the same when we are executing it, I was assuming it is not depending on the sequence but the parameter name and i was wrong.

Related

Fill a table from CSV file with stored procedure

I want to import data from this SQL table:
CREATE TABLE [dbo].[TempExchangeRates](
[currency (Libellés)] [nvarchar](255) NULL,
[Currency Code] [nvarchar](255) NULL,
[2019-03] [float] NULL,
[2019-04] [float] NULL,
[2019-05] [float] NULL,
[2019-06] [float] NULL,
[2019-07] [float] NULL,
[2019-08] [float] NULL,
[2019-09] [float] NULL,
[2019-10] [float] NULL,
[2019-11] [float] NULL,
[2019-12] [float] NULL,
[2020-01] [float] NULL,
[2020-02] [float] NULL
)
With sample data:
To this one:
CREATE TABLE [dbo].[ExchangeRates]
(
[IdExchangeRate] [uniqueidentifier] NOT NULL,
[ExchangeRateCode] [nvarchar](10) NULL,
[ExchangeRatePeriodStartDate] [datetime] NULL,
[ExchangeRatePeriodEndDate] [datetime] NULL,
[ExchangeRateValue] [decimal](20, 5) NULL,
[CurrencyCode] [nvarchar](10) NULL,
)
Now I want to call a stored procedure to get fill the real table like that:
I start with stored procedure like that but I'm not sure how I could do that
------------------------- 3. Declare StartDateTable --------------------
DECLARE #StartDateExchangeRate TABLE
(
rowid INT IDENTITY(1,1) NOT NULL,
value float,
startDate date
)
-- Insert Into #StartDateExchangeRate(value, startDate)
--This finds the start dates by finding unmatched values
--SELECT id,value
-- from ExchangeRates
------------------------- 2. Declare EndDateTable --------------------
DECLARE #EndDateExchangeRate TABLE
(
EndDate date
)
Insert Into #ENdDateExchangeRate(EndDate)
--This finds the start dates by finding unmatched values
SELECT EOMONTH(startdate)
FROM #StartDateExchangeRate As ER1
-------------------------3. Join NotYet--------------------------
This question is lacking in details
Assuming the TempExchangeRates columns will vary as time goes on, here is a option that will dynamically UNPIVOT the data so it can be inserted into your final structure.
Example (or dbFiddle)
Select ExchangeRateCode = A.[Currency Code]
,ExchangeRatePeriodStartDate = period
,ExchangeRatePeriodEndDate = EOMonth(period)
,ExchangeRateValue = B.Value
,CurrencyCode = replace(upper(A.[currency (Libellés)]),' ','')
,CreatedBy = 'SomeString'
,CreatededAt = getdate()
From [TempExchangeRates] A
Cross Apply ( Select period = try_convert(date,[Key]+'-01')
,Value = try_convert(float,value)
From OpenJson((Select A.* For JSON Path,Without_Array_Wrapper ))
Where [Key] not in ('currency (Libellés)','Currency Code')
) B
Returns

Dynamically insert into table using sp_executesql in SQL Server

I got error
Msg 207, Level 16, State 1, Line 33
Invalid column name 'Front Brakes1'
when executing a stored procedure which looks like this:
DECLARE #SqlStatement NVARCHAR(MAX);
SET #SqlStatement = 'INSERT INTO [SalesLT].[Product]('+ #Column+ ') VALUES('+#Value+')';
PRINT #SqlStatement
EXEC sys.sp_executesql #SqlStatement, N'#Column NVARCHAR(MAX), #Value NVARCHAR(MAX)',#Column,#Value
PRINT #SqlStatement results in:
INSERT INTO [SalesLT].[Product](Name, ProductNumber, Color, StandardCost, ListPrice, Weight)
VALUES ("Front Brakes1", "FB-98731", "Silver1", 47.286, 106.5, 317)
Additionally, here is the table design I wanna insert data into:
CREATE TABLE [SalesLT].[Product]
(
[ProductID] [INT] IDENTITY(1,1) NOT NULL,
[Name] [dbo].[Name] NOT NULL,
[ProductNumber] [NVARCHAR](25) NOT NULL,
[Color] [NVARCHAR](15) NULL,
[StandardCost] [MONEY] NOT NULL,
[ListPrice] [MONEY] NOT NULL,
[Size] [NVARCHAR](5) NULL,
[Weight] [DECIMAL](8, 2) NULL,
[ProductCategoryID] [INT] NULL,
[ProductModelID] [INT] NULL,
[SellStartDate] [DATETIME] NOT NULL,
[SellEndDate] [DATETIME] NULL,
[DiscontinuedDate] [DATETIME] NULL,
[ThumbNailPhoto] [VARBINARY](MAX) NULL,
[ThumbnailPhotoFileName] [NVARCHAR](50) NULL,
[rowguid] [UNIQUEIDENTIFIER] ROWGUIDCOL NOT NULL,
[ModifiedDate] [DATETIME] NOT NULL,
)
Enclose the T-SQL string literals in single quotes instead of double-quotes so that the resultant SQL statement is:
INSERT INTO [SalesLT].[Product](Name,ProductNumber,Color,StandardCost,ListPrice,Weight)
VALUES('Front Brakes1','FB-98731','Silver1',47.286,106.5,317);
Double-quotes (or square brackets) denote identifiers, such as table and column names.

SQL Server Always Encrypted Operand type clash: varchar is incompatible with varchar(60) when running EXEC sproc

I am unable to EXEC a stored procedure that upserts a table that has an encrypted column using Always Encrypted. However, I am able to copy the SQL from the sproc and run that as regular SQL with the parameters set, Just cannot get the sproc to fire when executing the sproc via the EXEC function in SSMS which is also causing problems in the application
The table has a trigger on it that inserts into another audit table of similar structure that is also encrypted using the same encryption. I have done the usual thing:
Checking the Enable Parameterizaion for Always Encrypted in Query Options Setting column encryption setting=enabled on the Connection Settings.
Refreshing the encyrption metadata for the sproc:
EXEC sp_refresh_parameter_encryption 'organization.uspOrganizationAddressUpsert'
Tables:
CREATE TABLE [organization].[OrganizationAddress](
[OrganizationAddressId] [int] IDENTITY(1,1) NOT NULL,
[CreatedUser] [int] NOT NULL,
[CreatedDate] [datetime2](7) NOT NULL,
[LastUpdateUser] [int] NOT NULL,
[LastUpdateDate] [datetime2](7) NOT NULL,
[RemovedDate] [datetime2](7) NULL,
[Address1] [varchar](60) NOT NULL,
[Address2] [varchar](60) NULL,
[City] [varchar](60) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [CEK_Auto1], ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL,
[State] [varchar](60) NOT NULL,
[ZipCode] [varchar](60) NOT NULL,
[ClientNumberId] [int] NOT NULL
CREATE TABLE [audit].[OrganizationAddressAudit](
[OrganizationAddressId] [int] NOT NULL,
[CreatedUser] [int] NOT NULL,
[CreatedDate] [datetime2](7) NOT NULL,
[LastUpdateUser] [int] NOT NULL,
[LastUpdateDate] [datetime2](7) NOT NULL,
[RemovedDate] [datetime2](7) NULL,
[Address1] [varchar](60) NOT NULL,
[Address2] [varchar](60) NULL,
[City] [varchar](60) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [CEK_Auto1], ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL,
[State] [varchar](60) NOT NULL,
[ZipCode] [varchar](60) NOT NULL,
[ClientNumberId] [int] NOT NULL,
[OperationDate] [datetime] NOT NULL,
[Operation] [varchar](50) NOT NULL,
[OperationBy] [varchar](100) NOT NULL
Stored Procedure:
ALTER PROCEDURE [organization].[uspOrganizationAddressUpsert]
#OrganizationId INT,
#ExecutingUserId INT,
#Address1 VARCHAR(60),
#Address2 VARCHAR(60),
#City VARCHAR(60),
#State VARCHAR(60),
#ZipCode VARCHAR(60),
#ClientNumberId INT
AS
BEGIN
SET NOCOUNT ON
DECLARE #RightNow AS DATETIME2 = SYSDATETIME()
If EXISTS (Select 1 From [organization].[OrganizationAddress] Where ClientNumberId = #ClientNumberId)
BEGIN
UPDATE [organization].[OrganizationAddress] SET
LastUpdateUser = #ExecutingUserId,
LastUpdateDate = #RightNow,
Address1 = #Address1,
Address2 = #Address2,
City = #City,
[State] = #State,
ZipCode = #ZipCode,
RemovedDate = Null
Where ClientNumberId = #ClientNumberId
END
ELSE
BEGIN -- INSERT part of the UPSERT
INSERT INTO [organization].[OrganizationAddress]
(CreatedUser
,CreatedDate
,LastUpdateUser
,LastUpdateDate
,Address1
,Address2
,City
,[State]
,ZipCode
,ClientNumberId)
VALUES
(#ExecutingUserId
,#RightNow
,#ExecutingUserId
,#RightNow
,#Address1
,#Address2
,#City
,#State
,#ZipCode
,#ClientNumberId)
END
END
Running the stored procedure code with the paramteers set is fine, but I am unable to EXEC the sproc:
declare #orgId INT = 1;
declare #client int = 888;
declare #user int = 1;
declare #Add1 varchar(60)= 'Test Address1';
declare #Add2 varchar(60)= 'Test Address2';
declare #city varchar(60) = 'City';
declare #state varchar(60) = 'St';
declare #zip varchar(60) = '12345';
EXEC organization.uspOrganizationAddressUpsert
#OrganizationID=#orgID,
#ExecutingUserId = #user, -- int
#Address1 = #Add1, -- varchar(60)
#Address2 = #Add2, -- varchar(60)
#City = #city, -- varchar(60)
#State = #state, -- varchar(60)
#ZipCode = #zip, -- varchar(60)
#ClientNumberId = #client; -- int
Msg 206, Level 16, State 2, Procedure uspOrganizationAddressUpsert, Line 0 [Batch Start Line 1]
Operand type clash: varchar is incompatible with varchar(60) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto1', column_encryption_key_database_name = 'BankruptcyApp') collation_name = 'SQL_Latin1_General_CP1_CI_AS'
I created a similar table in a test DB with VARCHAR(60) for the enrcrypted columns, a trigger, and an audit table and its working fine there and I cant find any differences in the table/sproc/trigger that would allow it to work there and not here. I've pretty much exhausted the other posts and blogs I can find.
Fixed! Needed to update the app code to specify the data type and length:
parameters.Add("#City", organizationAddress.City, System.Data.DbType.AnsiString, System.Data.ParameterDirection.Input, 60);
where it was previously just:
parameters.Add("#City", organizationAddress.City)
This at least get the app to run the sproc but still cant run it from SSMS via EXEC

The wait operation timed out

I have 2 tables,each contains 4-500k records
CREATE TABLE [dbo].[User][UserId] [int] IDENTITY(1,1) NOT NULL,
[Password] [nvarchar](max) NULL,
[RoleId] [int] NOT NULL,
[Name] [nvarchar](max) NULL,
[Address] [nvarchar](max) NULL,
[Email] [nvarchar](max) NULL,
[Landline] [nvarchar](max) NULL,
[MobileNumberCode] [int] NULL,
[MobileNumber] [nvarchar](max) NULL,
[DateOfBirth] [datetime] NULL,
[MarriageDate] [datetime] NULL,
[CreatedDate] [datetime] NOT NULL,
[UpdatedDate] [datetime] NOT NULL,
[Status] [nvarchar](max) NOT NULL,
[BranchId] [int] NULL,
[UserTitle] [nvarchar](50) NULL,
[MiddleName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[HouseNumber] [nvarchar](50) NULL,
[BuildingNumber] [nvarchar](50) NULL,
[RoadNumber] [nvarchar](50) NULL,
[BlockNumber] [nvarchar](50) NULL,
[City] [nvarchar](50) NULL,
[NearBranchId] [int] NULL,
[MobileIsValid] [bit] NULL,
[EmailIsValid] [bit] NULL,
[Gender] [nvarchar](50) NULL,
[SourceId] [int] NULL)
CREATE TABLE [dbo].[PurchaseOrder]
[PurchaseOrderId] [int] NOT NULL,
[BranchId] [int] NOT NULL,
[PurchaseDate] [datetime] NOT NULL,
[Amount] [decimal](18, 3) NOT NULL,
[UserId] [int] NOT NULL,
[Status] [nvarchar](max) NULL,
[sbs_no] [int] NOT NULL)
And I have stored procedure to get data from these tables using join.
CREATE PROC Sp_SearchCustomer (#FromDate datetime = null,
#ToDate datetime = null,
#RegFromDate datetime = null,
#RegToDate datetime = null)
AS
BEGIN
select a.UserId,a.Name,b.PurchaseOrderId,b.Amount from dbo.[User] a left join PurchaseOrder b on a.UserId=b.UserId
where
((a.CreatedDate >= ''' + cast(#RegFromDate as varchar) + ''')
AND (a.CreatedDate <= ''' + cast(#RegToDate as varchar) + '''))
and ((b.PurchaseDate >= ''' + cast(#FromDate as varchar) + ''')
AND (b.PurchaseDate <= ''' + cast(#ToDate as varchar) + '''))
END
When executing this procedure with date, its getting "The wait operation timed out" exception. Please help to solve this issue.
Your date in your tables and in your Procedure are both saved as varchar. This is perfect and there is no need to convert them to varchar.
Beside, varchar is surrounded by quotes and won't be executed. This is just becoming a string:
where ((a.CreatedDate >= 'cast(#RegFromDate as varchar)')...
There are also way too many useless parenthesis since you are using AND.
Try this instead:
CREATE PROC Sp_SearchCustomer (
#FromDate datetime = null,
#ToDate datetime = null,
#RegFromDate datetime = null,
#RegToDate datetime = null
)
AS
BEGIN
SELECT a.UserId
,a.Name
,b.PurchaseOrderId
,b.Amount
FROM dbo.[User] a
LEFT JOIN PurchaseOrder b
ON a.UserId = b.UserId
WHERE
a.CreatedDate >= #RegFromDate
AND a.CreatedDate <= #RegToDate
AND b.PurchaseDate >= #FromDate
AND b.PurchaseDate <= #ToDate
END
Once the query has been improved, you can test it again.
You should also look at Statistics and Indexes and make sure that Statistics are up-to-date and Indexes are not fragmented.
For Statistics, you can use: exec sp_updatestats
For Indexes on these 2 tables, look at the Fragmentation % and choose to REBUILD or REORGANIZE them.

SQL Trigger - How to update a table whenever another table in another database is being updated?

So I have a table called "persons" in a database test1:
CREATE TABLE [dbo].[persons](
[ID] [int] IDENTITY(1,1) NOT NULL,
[LastName] [varchar](50) NULL,
[FirstName] [varchar](50) NULL,
[Job] [varchar](50) NULL,
[Extension] [char](10) NULL,
[EMail] [varchar](50) NULL,
[Dept] [int] NULL,
[MobileNumber] [char](10) NULL,
[District] [int] NULL,
[Status] [varchar](50) NULL,
[InOutStatus] [varchar](5) NULL,
[InOutDescr] [varchar](50) NULL,
[InOutDirections] [varchar](255) NULL,
[InOutReturn] [varchar](50) NULL,
[login] [varchar](50) NULL,
[StatusExpiry] [datetime] NULL
) ON [PRIMARY]
And a table called "Users" in a database test2:
CREATE TABLE [dbo].[Users](
[User_ID] [int] NOT NULL,
[Firstname] [nvarchar](50) NULL,
[Lastname] [nvarchar](50) NULL,
[Username] [nvarchar](50) NULL,
[Status] [nvarchar](50) NULL
) ON [PRIMARY]
What I'm trying to do is create a Trigger where if the FirstName, LastName, login, and/or Status column in the persons table is updated, then the same value is updated in its identical column in the Users table. This is a Trigger I came up with but it doesn't work:
ALTER TRIGGER [dbo].[UserUpdteTrig]
ON [dbo].[persons]
AFTER UPDATE
AS
BEGIN
DECLARE #uid int;
DECLARE #fname nvarchar(50);
DECLARE #lname nvarchar(50);
DECLARE #uname nvarchar(50);
DECLARE #stat nvarchar(50);
SELECT #fname = i.FirstName, #lname = i.LastName, #uname = i.login, #stat = i.Status
FROM inserted i
UPDATE [test2].[dbo].[Users]
SET Firstname = #fname , Lastname = #lname, Username = #uname, Status = #stat
FROM [test2].[dbo].[Users] u INNER JOIN inserted i ON u.User_ID = i.ID
END
I keep getting an error that says: The row value updated and deleted either do not make the row unique or they alter multiple rows, which the PK in both tables are all unique and the PK shouldn't be altered anyway.
You dont need any variables at all just a simple update should be enough.
ALTER TRIGGER [dbo].[UserUpdteTrig]
ON [dbo].[persons]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE u
SET u.Firstname = i.FirstName
, u.Lastname = i.Lastname
, u.Username = i.Username
, u.[Status] = i.[Status]
FROM [test2].[dbo].[Users] u
INNER JOIN inserted i ON u.[User_ID] = i.ID
END

Resources