SQL Server : unable to save decimal digits - sql-server

I am facing a peculiar problem. I have a few tables in SQL Server where I have properly declared a few columns as decimal(18, 2).
Unfortunately, whenever, I save any value in these columns, either the values to the right of the value are not stored or are rounded off to the higher multiple and the value to the right of the decimal remains at 00.
I save these values through stored procedures where I have declared the decimal data type for such columns for the relevant parameters.
What could be the issue?
EDIT: posting the table script
CREATE TABLE [dbo].[ItemMaster]
(
[ColIndex] [int] IDENTITY(1,1) NOT NULL,
[ItemName] [nvarchar](150) NULL,
[ItemBrand] [int] NULL,
[ItemHSN] [nvarchar](50) NULL,
[ItemSalePrice] [decimal](18, 2) NULL,
[ItemCode] [nvarchar](50) NULL,
[ItemBarcode] [nvarchar](max) NULL,
[ItemQRCode] [nvarchar](max) NULL,
[ItemUnit] [int] NULL,
[ItemOpeningStock] [int] NULL,
[ItemCreationDate] [datetime] NULL,
[ItemEditDate] [datetime] NULL,
[ItemCreationUserID] [int] NULL,
[ItemEditUserID] [int] NULL,
[ItemActiveStatus] [int] NULL,
[PurCGST] [decimal](10, 3) NULL,
[PurSGST] [decimal](10, 3) NULL,
[PurIGST] [decimal](10, 3) NULL,
[SaleCGST] [decimal](10, 3) NULL,
[SaleSGST] [decimal](10, 3) NULL,
[SaleIGST] [decimal](10, 3) NULL,
[ItemCat] [int] NULL,
[RandomString] [nvarchar](50) NULL,
CONSTRAINT [PK_ItemMaster]
PRIMARY KEY CLUSTERED ([ColIndex] 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]
The stored procedure:
CREATE OR ALTER PROCEDURE [dbo].[EditItem]
#ItemColID BIGINT,
#ItemName NVARCHAR(150),
#ItemBrandNum INT,
#ItemHSN NVARCHAR (150),
#SalePrice DECIMAL,
#ItemCode NVARCHAR(150),
#ItemBarcode NVARCHAR(500),
#ItemQRCode NVARCHAR(500),
#ItemUnitNum INT,
#ItemOpeningStock INT,
-- #ItemCreateDate DATETIME,
#ItemEditDate DATETIME,
-- #ItemCreateUserID INT,
#ItemEditUserID INT,
#ItemActiveStatus INT,
-- #PurCGSTRate DECIMAL,
-- #PurSGSTRate DECIMAL,
-- #PurIGSTRate DECIMAL,
#SaleCGSTRate DECIMAL,
#SaleSGSTRate DECIMAL,
#SaleIGSTRate DECIMAL,
#ItemCat INT
AS
BEGIN
SET NOCOUNT ON;
UPDATE ItemMaster
SET ItemName = #ItemName ,
ItemBrand = #ItemBrandNum,
ItemHSN = #ItemHSN,
ItemSalePrice = #SalePrice,
ItemCode = #ItemCode,
ItemBarcode = #ItemBarcode ,
ItemQRCode = #ItemQRCode ,
ItemUnit = #ItemUnitNum ,
ItemOpeningStock= #ItemOpeningStock ,
-- #ItemCreateDate
ItemEditDate = #ItemEditDate ,
-- #ItemCreateUserID
ItemEditUserID = #ItemEditUserID ,
ItemActiveStatus = #ItemActiveStatus,
-- purcgst=#PurCGSTRate ,
--pursgst=#PurSGSTRate ,
--purigst=#PurIGSTRate,
salecgst= #SaleCGSTRate ,
SaleSGST = #SaleSGSTRate ,
saleigst= #SaleIGSTRate,
itemcat = #ItemCat
WHERE ItemMaster .ColIndex = #ItemColID
END
GO

Parameter of type DECIMAL is equal to DECIMAL(18,0):
#SaleCGSTRate DECIMAL,
#SaleSGSTRate DECIMAL,
#SaleIGSTRate DECIMAL,
This is WITHOUT any digits after the decimal point!!
You need to be explicit about your datatype - for the parameters as well !
So you need to use DECIMAL(18,2) as the datatype for your stored procedure parameters - THEN you will be able to store fractional decimal values just fine!
See the official MS documentation on DECIMAL in SQL Server for more details.
This is from the official docs (my highlights):
decimal[ (p[ ,s] )]
p (precision)
The maximum total number of decimal digits to be stored. This number includes both the left and the right sides of the decimal point. The precision must be a value from 1 through the maximum precision of 38. The default precision is 18.
s (scale)
The number of decimal digits that are stored to the right of the decimal point. This number is subtracted from p to determine the maximum number of digits to the left of the decimal point. Scale must be a value from 0 through p, and can only be specified if precision is specified. The default scale is 0 and so 0 <= s <= p. Maximum storage sizes vary, based on the precision.

Related

If Else statement on T-SQL calculated column

I have a table I'm creating for an app I'm making and want to populate a calculated column from an IF statement,I don't know how to write the T-SQL for it and have looked for an answer but can't find
What i'm looking for is basically
IF (Close<=Open)
[CloseLessEqualToOpen == Yes]
ELSE
[CloseLessEqualToOpen == No]
T-SQL
CREATE TABLE [dbo].[LowFloatStocks] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Date] DATE NOT NULL,
[Ticker] NCHAR (10) NOT NULL,
[PreviousClose] DECIMAL (4, 2) DEFAULT ((4.00)) NOT NULL,
[OpeningPrice] DECIMAL (18, 2) NOT NULL,
[GainPercent] AS (round(([High]-[OpeningPrice])/[OpeningPrice],(4))*(100.0)) PERSISTED NOT NULL,
[GapPercent] AS (round(([OpeningPrice]-[PreviousClose])/[PreviousClose],(4))*(100.0)) PERSISTED NOT NULL,
[Spike] DECIMAL (18, 2) NOT NULL,
[1stSpike%] AS (round(([Spike]-[OpeningPrice])/[OpeningPrice],(4))*(100.0)) PERSISTED NOT NULL,
[High] DECIMAL (18, 2) NOT NULL,
[HighPercent] AS (round(([High]-[PreviousClose])/[PreviousClose],(4))*(100.0)) PERSISTED NOT NULL,
[Low] DECIMAL (18, 2) NOT NULL,
[LowPercent] AS (round(([Low]-[PreviousClose])/[PreviousClose],(4))*(100.0)) PERSISTED NOT NULL,
[Close] DECIMAL (18, 2) DEFAULT ((4)) NOT NULL,
[ClosePercent] AS (round(([Close]-[PreviousClose])/[PreviousClose],(4))*(100.0)) PERSISTED NOT NULL,
[CloseLessEqualToOpen] NCHAR (3) NULL,
[CloseRed] NCHAR (3) NULL,
[ClosevHigh] AS (round(([High]-[Close])/[Close],(4))*(100)) PERSISTED NOT NULL,
[ClosevOpen] AS (round(([OpeningPrice]-[Close])/[OpeningPrice],(4))*(100.0)) PERSISTED NOT NULL,
[Catalyst] NVARCHAR (50) NOT NULL,
[Float] DECIMAL (18, 3) NOT NULL,
[Dilution] NCHAR (3) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
First of all, you need to get a single value to use in your statement:
DECLARE #Close DECIMAL (18, 2);
SET #Close = (SELECT TOP 1 Close FROM [dbo].[LowFloatStocks]);
For above statement, you can also apply WHERE or any other clause based on your need.
Then use SQL IF statement to do your comparisons, this way:
IF(#Close <= Open) -- assuming that Open is declared somewhere else
BEGIN
-- Your logic here
PRINT #Close
END
ELSE
BEGIN
-- Your logic here
PRINT #Close
END
Later you can update your Table this way:
UPDATE
[dbo].[LowFloatStocks]
SET
CloseLessEqualToOpen = ...
WHERE
...
However, there is also a more elegant solution in case if you want to make the calculation process happen automatically.
For that reason you can use Computed Columns:
CREATE TABLE [dbo].[LowFloatStocks]
(
[Close] DECIMAL (18, 2) DEFAULT ((4)) NOT NULL,
[Open] DECIMAL (18, 2) DEFAULT ((4)) NOT NULL,
-- other columns declaration here
[CloseLessEqualToOpen] AS CAST
(
CASE WHEN [Close] <= [Open] THEN 'Yes' ELSE 'No' END AS NVARCHAR(10)
)
)

Convert SQL server to Teradata Query

I want to convert the following SQL server query into a Teradata BTEQ script. Could anyone help in this process..
The table creation logic is as follows and this needs to be converted to Teradata
CREATE TABLE [Eqp].[t_WSTCPEStairstep]
(
[SysID] [smallint] NULL,
[PrinID] [smallint] NULL,
[Account] [bigint] NOT NULL,
[Order_No] [bigint] NOT NULL,
[Order_Typ] [varchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Eqp_Serial] [varchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Eqp_Typ] [varchar] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Eqp_Model] [varchar] (9) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Disco_Dte] [date] NULL,
[Return_Dte] [date] NULL,
[Restart_Dte] [date] NULL,
[Lost_Dte] [date] NULL,
[TestFlag] [smallint] NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
GO
CREATE NONCLUSTERED INDEX [ix_WSTCPEStairstepDiscoDteIndex] ON [Eqp].[t_WSTCPEStairstep] ([Disco_Dte]) ON [PRIMARY]
GO
CREATE CLUSTERED INDEX [ix_WSTCPEStairstepSPAIndex] ON [Eqp].[t_WSTCPEStairstep] ([SysID], [Account]) WITH (DATA_COMPRESSION = PAGE) ON [PRIMARY]
GO
I'm not sure about some of the SQL Server specific bits (compression, clustered, primary), but this will give you a start:
CREATE TABLE Eqp.t_WSTCPEStairstep (
SysID SMALLINT,
PrinID SMALLINT,
Account BIGINT NOT NULL,
Order_No BIGINT NOT NULL,
Order_Typ VARCHAR(1),
Eqp_Serial VARCHAR(25),
Eqp_Typ VARCHAR(2),
Eqp_Model VARCHAR(9) ,
Disco_Dte DATE,
Return_Dte DATE,
Restart_Dte DATE,
Lost_Dte DATE,
TestFlag SNALLINT
)
PRIMARY INDEX(col1, col2, ...);
-- Indexes
CREATE INDEX ix_WSTCPEStairstepDiscoDteIndex (Disco_Dte) ON Eqp.t_WSTCPEStairstep;
CREATE INDEX ix_WSTCPEStairstepSPAIndex (SysID, Account) ON Eqp.t_WSTCPEStairstep;
Which column(s) do you use to access data in this table? If they provide even distribution (i.e. mostly distinct values), then specify these as your PRIMARY INDEX fields. And if these fields are unique, better yet - UNIQUE PRIMARY INDEX. Maybe it's one of the indexes you specified -- disco_dte or (SysID, Account).
Some more notes:
columns should be NULLABLE by default
if TestFlag is just 1/0, you can use the BYTEINT data type
you may want to convert the VARCHAR(1) and VARCHAR(2) to CHAR
for compression, you can add that at multiple levels, but most common I think is at the column level

Crazy "String or binary data would be truncated" error with correct type and length

I have a table with following table structure;
CREATE TABLE [dbo].[SALES](
[COLUMN1] [numeric](18, 0) NOT NULL,
[COLUMN2] [varchar](11) NOT NULL,
[COLUMN3] [numeric](18, 0) NULL,
[COLUMN4] [numeric](18, 0) NULL,
[COLUMN5] [datetime] NULL,
[COLUMN6] [datetime] NULL,
[COLUMN7] [numeric](18, 0) NULL,
[COLUMN8] [numeric](18, 0) NULL,
[COLUMN9] [smallint] NULL,
[COLUMN10] [smallint] NULL,
[COLUMN11] [datetime] NULL,
[COLUMN12] [varchar](30) NULL,
[COLUMN13] [smallint] NULL,
[COLUMN14] [varchar](20) NULL CONSTRAINT [DF__SALES_DATA__3F3D11FA] DEFAULT (null),
[COLUMN15] [smallint] NOT NULL CONSTRAINT [DF_SALES_anonymous] DEFAULT ((0)),
[COLUMN16] [numeric](18, 0) NULL,
[COLUMN17] [varchar](11) NULL,
[COLUMN18] [smallint] NULL,
[COLUMN19] [varchar](100) NULL,
[COLUMN20] [datetime] NULL,
CONSTRAINT [XPKSALES] PRIMARY KEY CLUSTERED
(
[COLUMN1] 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]
However, when I update the value with 11 characters into the COLUMN17 (Note that the column length is 11), the SQL Server throws following error. I am using SQL Server 2014.
String or binary data would be truncated.
However, I have created a table with one column having a length of 11 characters and inserted value with 11 characters. It was successfully inserted, then update the same value. Update too success.
Can someone help me to identify the issue?
UPDATE
For some reason, the only way to solve it was casting the value
UPDATE SALES SET Column17 = CAST( '89000107051' AS VARCHAR(11))
Can someone explain why was necessary to do that for a plain varchar value with the proper length?
Note: Triggers is not the answer

SQL Server Always Encrypted: Operand type clash: varchar is incompatible with varchar(max)

As we have regulation changes coming in force in the UK soon a database that I am working on that needs to be updated to have any personal identifiable information encrypted.
A number of my tables have been altered successfully, however on some tables where there are triggers I am getting the following error.
Error SQL72014: .Net SqlClient Data Provider: Msg 206, Level 16, State 2, Procedure tr_Employee_Update, Line 27 Operand type clash: varchar is incompatible with varchar(max) 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 = 'xxxx') collation_name = 'Latin1_General_BIN2'
I have looked at this question here, however this doesnt solve my issue Operand type clash: varchar is incompatible with varchar(50) trying to insert in encrypted database
Same with this question too where is doesnt address my issue exactly. SQL Server Always Encrypted Operand type clash: varchar is incompatible with varchar(60) when running EXEC sproc.
I have this issue on a number of tables so would be grateful for any and all help.
Please see the SQL Fiddle here
http://sqlfiddle.com/#!18/4ac5c/3
I have had to split the table and trigger creation because the SQL length is greater than 8000 characters but this is the fullest example I can give.
I am encrypting the columns using Encryption type: Deterministic and Encryption key name: CEK_Auto1.
Not all columns in this table need encrypting and I am altering some of the other fields that have default values too where encryption does need to take place.
Any and all help on the reported issue would be gratefully received.
CREATE TABLE [dbo].[Employee] (
[EmployeeID] INT IDENTITY (1, 1) NOT NULL,
[EmployeeTypeID] INT NOT NULL,
[Title] VARCHAR (50) NOT NULL,
[Forename] VARCHAR (30) NOT NULL,
[Surname] VARCHAR (30) NOT NULL,
[AddressLine1] VARCHAR (60) NOT NULL,
[AddressLine2] VARCHAR (60) NOT NULL,
[AddressLine3] VARCHAR (60) NOT NULL,
[AddressLine4] VARCHAR (60) NOT NULL,
[Town] VARCHAR (50) NOT NULL,
[County] VARCHAR (50) NOT NULL,
[PostCode] VARCHAR (20) NOT NULL,
[Phone] VARCHAR (20) CONSTRAINT [DF_Employee_Phone] DEFAULT ('') NOT NULL,
[Mobile] VARCHAR (20) NOT NULL,
[Fax] VARCHAR (20) NOT NULL,
[Email] VARCHAR (50) NOT NULL,
[Extension] VARCHAR (10) CONSTRAINT [DF_Employee_Extension_1] DEFAULT ('') NOT NULL,
[SpeedDial] VARCHAR (10) CONSTRAINT [DF_Employee_SpeedDial_1] DEFAULT ('') NOT NULL,
[Notes] VARCHAR (MAX) NOT NULL,
[EmployeeTeamID] INT NULL,
[Created] DATETIME CONSTRAINT [DF_Employee_Created] DEFAULT (getdate()) NOT NULL,
[OperatorIDCreated] INT NOT NULL,
[Updated] DATETIME CONSTRAINT [DF_Employee_Updated] DEFAULT (getdate()) NOT NULL,
[OperatorIDUpdated] INT NOT NULL,
[Deleted] BIT CONSTRAINT [DF_Employee_Deleted] DEFAULT ((0)) NOT NULL,
[EmployeeIDManager] INT NULL,
[JobTitle] VARCHAR (100) CONSTRAINT [DF_Employee_JobTitle] DEFAULT ('') NOT NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([EmployeeID] ASC),
CONSTRAINT [FK_Employee_Employee] FOREIGN KEY ([EmployeeIDManager]) REFERENCES [dbo].[Employee] ([EmployeeID]),
CONSTRAINT [FK_Employee_EmployeeTeam] FOREIGN KEY ([EmployeeTeamID]) REFERENCES [dbo].[EmployeeTeam] ([EmployeeTeamID]),
CONSTRAINT [FK_Employee_EmployeeType] FOREIGN KEY ([EmployeeTypeID]) REFERENCES [dbo].[EmployeeType] ([EmployeeTypeID])
);
GO
CREATE NONCLUSTERED INDEX [IX_Employee_Surname]
ON [dbo].[Employee]([Surname] ASC);
GO
CREATE TABLE [dbo].[AuditItem](
[AuditItemID] [INT] IDENTITY(1,1) NOT NULL,
[ID] [INT] NOT NULL,
[AuditEntityID] [INT] NOT NULL,
[AuditTypeID] [INT] NOT NULL,
[Note] [VARCHAR](MAX) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [CEK_Auto1], ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL,
[Created] [DATETIME] NOT NULL,
[OperatorIDCreated] [INT] NOT NULL,
[ProfessionalIDCreated] [INT] NULL,
CONSTRAINT [PK_AuditItem] PRIMARY KEY CLUSTERED
(
[AuditItemID] 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 Trigger [dbo].[tr_Employee_Update] ON [dbo].[Employee]
FOR UPDATE
AS
--Audit Entity ID for Employees
Declare #AuditEntityID int
set #AuditEntityID = 2
Insert AuditItem
(ID,AuditEntityID,AuditTypeID, Note, Created, OperatorIDCreated)
Select
inserted.EmployeeID,
#AuditEntityID,
--Update type
2,
'Name changed from ' + ltrim(rtrim(ltrim(rtrim(Deleted.Title)) + ' ' + ltrim(rtrim(Deleted.Forename)) + ' ' + ltrim(rtrim(Deleted.Surname)))) + ' to ' + + ltrim(rtrim(ltrim(rtrim(Inserted.Title)) + ' ' + ltrim(rtrim(Inserted.Forename)) + ' ' + ltrim(rtrim(Inserted.Surname)))),
GetDate(),
inserted.OperatorIDUpdated
From inserted
Inner Join deleted on inserted.EmployeeID = deleted.EmployeeID
Where deleted.Title <> inserted.Title or deleted.Forename <> inserted.Forename or deleted.Surname <> inserted.Surname
After much research into this today it is unfortunate at the moment that triggers are not supported to update Encrypted Columns regardless of the data type. So anyone who stumbled across this question and is having the same issue you will need to complete your updates through stored procedures but they will need to be called via application code.
Although the two linked questions in my question above do not directly address my question or help me, you may need to follow the answers in the questions to help you should you need to pass parameterised values to a stored procedure and have issues.

stored procedure is execution taking long time in sql server

I have a table called Transaction_tbl with more than 400 000 records in it. This is the table structure:
CREATE TABLE [dbo].[Transaction_tbl](
[transactID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[TBarcode] [varchar](20) NULL,
[cmpid] [int] NULL,
[Locid] [int] NULL,
[PSID] [int] NULL,
[PCID] [int] NULL,
[PCdID] [int] NULL,
[PlateNo] [varchar](20) NULL,
[vtid] [int] NULL,
[Compl] [bit] NULL,
[self] [bit] NULL,
[LstTic] [bit] NULL,
[Gticket] [int] NULL,
[Cticket] [int] NULL,
[Ecode] [varchar](50) NULL,
[dtime] [datetime] NULL,
[LICID] [int] NULL,
[PAICID] [int] NULL,
[Plot] [varchar](50) NULL,
[mkid] [int] NULL,
[mdlid] [int] NULL,
[Colid] [int] NULL,
[Comments] [varchar](100) NULL,
[Kticket] [int] NULL,
[PAmount] [numeric](18, 2) NULL,
[Payid] [int] NULL,
[Paid] [bit] NULL,
[Paydate] [datetime] NULL,
[POICID] [int] NULL,
[DelDate] [datetime] NULL,
[DelEcode] [nvarchar](50) NULL,
[PAICdate] [datetime] NULL,
[KeyRoomDate] [datetime] NULL,
[Status] [int] NULL,
CONSTRAINT [PK_Transaction_tbl] PRIMARY KEY CLUSTERED
(
[transactID] 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
I have a nonclustered index on the Locid, dtime column.
I have a stored procedure like this:
ALTER procedure [dbo].[IBS_fetchreleasedinpodiumgridnew]
#locid INTEGER = NULL
AS BEGIN
SET NOCOUNT ON
DECLARE #TodayMinus7Days DATETIME
Declare #krrt integer
Declare #DT integer
SET #TodayMinus7Days = getdate()-1
SELECT
t.TBarcode, t.PlateNo, t.DelEcode,cast(t.Paydate as Time) [REQ],
datediff(MINUTE, t.PayDate,
CASE t.Status
WHEN 3 THEN GETDATE()
WHEN 4 THEN t.KeyRoomDate
When 5 THEN t.KeyRoomDate
End) as KRRT,
datediff(MINUTE,t.PayDate,
CASE t.Status
WHEN 3 THEN GETDATE()
WHEN 4 THEN GETDATE()
WHEN 5 THEN t.DelDate
END) as DT
FROM
dbo.Transaction_tbl t
WHERE
(
([status] IN (3,4))
OR
([status] = 5 AND DATEDIFF(n, DelDate, GETDATE()) <= 3)
)
AND locid = 6 AND dtime >= #TodayMinus7Days
ORDER BY
paydate
end
my execution plan like this:
but most of the time this is taking long time to execute ..in this case how i can improve my stored procedure execution performance?
any other method i want to use..any help is very appriciable.Thanks
the query execution plan is showing sorting is taking long time..so if i give index on paydate my query performance will increase?
instead of this dtime >= #TodayMinus7Days i given code like this:
dtime >= OPTION (optimize for (#TodayMinus7Days))
but getting error:Incorrect syntax near the keyword 'OPTION'.
Apart from optimizing the query, there are a couple things I can immediately suggest to improve the performance of a stored procedure.
Parameter sniffing: When the store procedure is passed a parameter, it analyses the dataset to figure out what would be the most efficient indexes. This is useful, though the plan is cached, and will get out of date, causing the stored proc to run on an inefficient execution plan.
Solution: Re-declare parameters or optimize the stored proc for unknown parameter values
Suppress the row count: One of the most simple things you can do to increase the performance of a stored procedure is SET NOCOUNT ON. This will prevent SQL Server from sending messages back to the client after the execution of each statement, which is not required for a stored proc. It seems like a small improvement, but the results are noticeable.
Solution: SET NOCOUNT ON
The snippet below has an example of where they go in your stored proc. Note that if you are re-declaring parameters, you don't need to optimize for unknown, and vice versa.
CREATE PROCEDURE dbo.example_proc
(
#USER_PARAM VARCHAR(200)
)
AS
BEGIN
-- suppress the number of rows returned
SET NOCOUNT ON;
-- Re-declaring the variable will prevent paramater sniffing
DECLARE #LOCAL_USER_PARAM VARCHAR(200) = #USER_PARAM
SELECT
*
FROM some_table st
WHERE st.some_column = #LOCAL_USER_PARAM
-- If you don't re-declare params, you can add this line
OPTION (OPTIMIZE FOR (#USER_PARAM UNKNOWN))
--
END
GO
Try using "with recompile" to get more suitable execution plan based on parameter. In my case it help reduce time from about 1 hours to a few minutes. Hope it work in your case as well.
exec [dbo].[IBS_fetchreleasedinpodiumgridnew] 1 with recompile
Check By Manually run the SP. If it is working fine than your problem is isolation level.
add these line in store procedure beginning.
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;

Resources