Delete and insert on same procedure - sql

In my SQL stored procedure, I need to delete and insert on same query. My syntax is below. But my syntax fails to store data. Why does it fail? How do I solve this problem? My syntax is
CREATE PROCEDURE spInsertCollectionInspectionHours
#StartDate DATETIME ,
#EndDate DATETIME ,
#ID BIGINT ,
#VesselName VARCHAR(80) ,
#VoyageNo VARCHAR(15) ,
#PortCode VARCHAR(20) ,
#Terminal VARCHAR(70) ,
#InspectionDate DATETIME ,
#InvoiceHours INT ,
#ManifestType INT ,
#Remarks NVARCHAR(200)
AS
BEGIN
BEGIN
DELETE FROM dbo.InspectionHours
WHERE InspectionDate BETWEEN #StartDate AND #EndDate
END
BEGIN
SELECT #ID = ISNULL(MAX(ID), 0) + 1
FROM [InspectionHours]
INSERT INTO [InspectionHours]
( [ID] ,
[VesselName] ,
[VoyageNo] ,
[PortCode] ,
[Terminal] ,
[InspectionDate] ,
[InvoiceHours] ,
[ManifestType] ,
[Remarks]
)
VALUES ( #ID ,
#VesselName ,
#VoyageNo ,
#PortCode ,
#Terminal ,
#InspectionDate ,
#InvoiceHours ,
#ManifestType ,
#Remarks
)
END
END
If have any questions please ask. Thanks in advance.

check your id field identity property is true or not if it's true or yes then no need to give id in insert statement

Your syntax is fine. This should not produce and error.
Your insert statement is also fine. If it is not throwing an error then something else is going on. Are you sure you are passing parameters? Are you sure you are looking in the correct server/db/table and using the correct query to check? Are you positive it's not throwing an error?

Related

SQL XMLNS failing with sp_executesql sproc

I have the following:
DECLARE #csXml XML
, #changeStatus XML
, #tNum NVARCHAR(25) = '0001aa17'
SELECT #csXml = ChangeSet
FROM [Issues]
WHERE [TrackingNumber] = #tNum
SET #changeStatus =
(
SELECT NEWID() AS [#id]
, 'me#sample.com' AS [#by]
, '1E910737-D78C-E711-9C04-00090FFE0001' AS [#byAccountId]
, '2018-01-18T18:39:03.220Z' AS [#when]
, 'Status' AS [property/#id]
, 'Status' AS [property/#name]
, 'In Review' AS [property/#old]
, 'Closed' AS [property/#new]
, '' AS [collections]
FOR XML PATH('change')
);
-- Add node to XML...
SET #csXml.modify(N'declare default element namespace "http://www.sample.com/ChangeSet/2017/09";
insert sql:variable("#changeStatus") as last into (/changes)[1]');
SET #ParamDef = N'#TrackingNumber NVARCHAR(25)
, #ChangeSet XML';
SET #sql = 'EXEC [SaveIssue] #TrackingNumber, #ChangeSet';
EXEC [sys].[sp_executesql] #sql
, #paramDef
, #TrackingNumber = #tNum
, #ChangeSet = #csXml;
I am getting back an error of:
Msg 6965, Level 16, State 1, Procedure SaveIssue, Line 27 XML
Validation: Invalid content. Expected element(s):
'{http://www.sample.com/ChangeSet/2017/09}change'. Found: element
'change' instead. Location: /:changes[1]/:change[4].
I understand that the sproc I am calling is throwing this error. What I cannot figure out is how to correctly call this sproc to make it stop! :)
The (truncated) definition for the sproc is:
CREATE PROCEDURE [SaveIssue]
( #TrackingNumber NVARCHAR(25)
, #ChangeSet XML(DOCUMENT Reference.sample) = N'<changes xmlns="http://www.sample.com/ChangeSet/2017/09" />'
)
AS
BEGIN
...
END
I have tried tying the XMLNS definition to the XML declaration(s), casting the final #csXml to XML and back to XML(DOCUMENT ...), etc. Nothing I am so far trying is working. I also tried a WITH XMLNAMESPACE... for the #changeStatus SELECT. I am a bit stumped!
Using a CTE solved this for me. First, I had to change the SET to a SELECT. Then added the WITH XMLNAMESPACE... portion. Here is the corrected piece to create the node I want to insert:
;WITH XMLNAMESPACES (DEFAULT 'http://www.sample.com/ChangeSet/2017/09')
SELECT #changeStatus =
(
SELECT NEWID() AS [#id]
, 'me#sample.com' AS [#by]
, '1E910737-D78C-E711-9C04-00090FFE0001' AS [#byAccountId]
, '2018-01-18T18:39:03.220Z' AS [#when]
, 'Status' AS [property/#id]
, 'Status' AS [property/#name]
, 'In Review' AS [property/#old]
, 'Closed' AS [property/#new]
, '' AS [collections]
FOR XML PATH('change')
);

SQL Merge - Number of Colums on Insert Must Match Number of Columns Specified

I am working with a stored procedure where I am using a Merge statement to do an insert or an update based on the conditions.
However when trying to compile the procedure I get the error
There are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.
However, I do believe that I have got the right number of columns, given that it was a copy and paste exercise from the insert into the values area.
Please see the Merge statement below and let me know how I am going wrong on this please
WITH CTE AS
(
SELECT
[PRNCPL_ACC_CD], [BRANCH_ACC_CD],
[COPY_MISC_DLR_FG], [COPY_LABR_HRS_FG],
[COPY_CSUM_COST_FG], [COPY_PART_PRICE_FG],
[COPY_TRVL_RATE_FG], [COPY_DISC_FG],
[COPY_TAX_RATE_FG], [COPY_REJ_RESN_FG],
[COPY_CNTR_OBLG_FG], [COPY_LABR_OVRS_FG]
FROM
CEQBP
WHERE
SHEDDULED_CHANGE_ID = CONVERT(CHAR(255), #SHEDDULED_CHANGE_ID)
)
MERGE INTO CEQBM AS T
USING CTE S ON T.PRNCPL_ACC_CD = S.PRNCPL_ACC_CD
AND T.BRANCH_ACC_CD = S.BRANCH_ACC_CD
WHEN MATCHED THEN
UPDATE
SET
T.[PRNCPL_ACC_CD] = S.[PRNCPL_ACC_CD],
T.[BRANCH_ACC_CD] = S.[BRANCH_ACC_CD],
T.[COPY_MISC_DLR_FG] = S.[COPY_MISC_DLR_FG],
T.[COPY_LABR_HRS_FG] = S.[COPY_LABR_HRS_FG],
T.[COPY_CSUM_COST_FG] = S.[COPY_CSUM_COST_FG],
T.[COPY_PART_PRICE_FG] = S.[COPY_PART_PRICE_FG],
T.[COPY_TRVL_RATE_FG] = S.[COPY_TRVL_RATE_FG],
T.[COPY_DISC_FG] = S.[COPY_DISC_FG],
T.[COPY_TAX_RATE_FG] = S.[COPY_TAX_RATE_FG],
T.[COPY_REJ_RESN_FG] = S.[COPY_REJ_RESN_FG],
T.[COPY_CNTR_OBLG_FG] = S.[COPY_CNTR_OBLG_FG],
T.[COPY_LABR_OVRS_FG] = S.[COPY_LABR_OVRS_FG]
WHEN NOT MATCHED THEN
INSERT ([PRNCPL_ACC_CD], [BRANCH_ACC_CD],
[COPY_MISC_DLR_FG], [COPY_LABR_HRS_FG],
[COPY_CSUM_COST_FG], [COPY_PART_PRICE_FG],
[COPY_TRVL_RATE_FG], [COPY_DISC_FG],
[COPY_TAX_RATE_FG], [COPY_REJ_RESN_FG],
[COPY_CNTR_OBLG_FG], [COPY_LABR_OVRS_FG])
VALUES (S.[PRNCPL_ACC_CD], S.[BRANCH_ACC_CD],
S.[COPY_MISC_DLR_FG], S.[COPY_LABR_HRS_FG],
S.[COPY_CSUM_COST_FG], S.[COPY_PART_PRICE_FG,
S.[COPY_TRVL_RATE_FG], S.[COPY_DISC_FG],
S.[COPY_TAX_RATE_FG], S.[COPY_REJ_RESN_FG],
S.[COPY_CNTR_OBLG_FG], S.[COPY_LABR_OVRS_FG]);
Edit with full scripts
User Defined Table Type
CREATE TYPE CEQBP_TYP AS TABLE(
[PRNCPL_ACC_CD] [char](10) ,
[BRANCH_ACC_CD] [char](10) ,
[COPY_MISC_DLR_FG] BIT DEFAULT(0) ,
[COPY_LABR_HRS_FG] BIT DEFAULT(0) ,
[COPY_CSUM_COST_FG] BIT DEFAULT(0) ,
[COPY_PART_PRICE_FG] BIT DEFAULT(0) ,
[COPY_TRVL_RATE_FG] BIT DEFAULT(0) ,
[COPY_DISC_FG] BIT DEFAULT(0) ,
[COPY_TAX_RATE_FG] BIT DEFAULT(0) ,
[COPY_REJ_RESN_FG] BIT DEFAULT(0) ,
[COPY_CNTR_OBLG_FG] BIT DEFAULT(0) ,
[COPY_LABR_OVRS_FG] BIT DEFAULT(0) ,
[EDIT_MISC_DLR_FG] BIT DEFAULT(0) ,
[EDIT_LABR_HRS_FG] BIT DEFAULT(0) ,
[EDIT_CSUM_COST_FG] BIT DEFAULT(0) ,
[EDIT_PART_PRICE_FG] BIT DEFAULT(0) ,
[EDIT_TRVL_RATE_FG] BIT DEFAULT(0) ,
[EDIT_DISC_FG] BIT DEFAULT(0) ,
[EDIT_TAX_RATE_FG] BIT DEFAULT(0) ,
[EDIT_REJ_RESN_FG] BIT DEFAULT(0) ,
[EDIT_CNTR_OBLG_FG] BIT DEFAULT(0) ,
[EDIT_LABR_OVRS_FG] BIT DEFAULT(0) ,
[SHEDULED_BY] VARCHAR (10) ,
[DATE_SCHEDULED] DATETIME DEFAULT(GETDATE()) ,
[EXECUTE_IMMEDIATELY] DATETIME DEFAULT(1)
)
GO
Stored Procedure
CREATE PROCEDURE sp_InsertCopyDataStagingData
#TVP CEQBP_TYP READONLY
AS
BEGIN
BEGIN TRY
BEGIN TRAN
DECLARE #SHEDDULED_CHANGE_ID uniqueidentifier = NEWID()
INSERT INTO CEQBP (
[SHEDDULED_CHANGE_ID]
,[PRNCPL_ACC_CD]
,[BRANCH_ACC_CD]
,[COPY_MISC_DLR_FG]
,[COPY_LABR_HRS_FG]
,[COPY_CSUM_COST_FG]
,[COPY_PART_PRICE_FG]
,[COPY_TRVL_RATE_FG]
,[COPY_DISC_FG]
,[COPY_TAX_RATE_FG]
,[COPY_REJ_RESN_FG]
,[COPY_CNTR_OBLG_FG]
,[COPY_LABR_OVRS_FG]
,[EDIT_MISC_DLR_FG]
,[EDIT_LABR_HRS_FG]
,[EDIT_CSUM_COST_FG]
,[EDIT_PART_PRICE_FG]
,[EDIT_TRVL_RATE_FG]
,[EDIT_DISC_FG]
,[EDIT_TAX_RATE_FG]
,[EDIT_REJ_RESN_FG]
,[EDIT_CNTR_OBLG_FG]
,[EDIT_LABR_OVRS_FG]
,[SHEDULED_BY]
,[DATE_SCHEDULED]
,[EXECUTE_IMMEDIATELY])
SELECT
CONVERT(char(255), #SHEDDULED_CHANGE_ID)
,[PRNCPL_ACC_CD]
,[BRANCH_ACC_CD]
,[COPY_MISC_DLR_FG]
,[COPY_LABR_HRS_FG]
,[COPY_CSUM_COST_FG]
,[COPY_PART_PRICE_FG]
,[COPY_TRVL_RATE_FG]
,[COPY_DISC_FG]
,[COPY_TAX_RATE_FG]
,[COPY_REJ_RESN_FG]
,[COPY_CNTR_OBLG_FG]
,[COPY_LABR_OVRS_FG]
,[EDIT_MISC_DLR_FG]
,[EDIT_LABR_HRS_FG]
,[EDIT_CSUM_COST_FG]
,[EDIT_PART_PRICE_FG]
,[EDIT_TRVL_RATE_FG]
,[EDIT_DISC_FG]
,[EDIT_TAX_RATE_FG]
,[EDIT_REJ_RESN_FG]
,[EDIT_CNTR_OBLG_FG]
,[EDIT_LABR_OVRS_FG]
,[SHEDULED_BY]
,[DATE_SCHEDULED]
,[EXECUTE_IMMEDIATELY]
FROM #TVP
IF (SELECT EXECUTE_IMMEDIATELY FROM CEQBP WHERE SHEDDULED_CHANGE_ID = CONVERT(char(255), #SHEDDULED_CHANGE_ID) ) = 1
BEGIN -- CALL STORED PROC TO RUN IMMEDIDATELY
WITH CTE AS (SELECT
[PRNCPL_ACC_CD]
,[BRANCH_ACC_CD]
,[COPY_MISC_DLR_FG]
,[COPY_LABR_HRS_FG]
,[COPY_CSUM_COST_FG]
,[COPY_PART_PRICE_FG]
,[COPY_TRVL_RATE_FG]
,[COPY_DISC_FG]
,[COPY_TAX_RATE_FG]
,[COPY_REJ_RESN_FG]
,[COPY_CNTR_OBLG_FG]
,[COPY_LABR_OVRS_FG]
FROM CEQBP WHERE
SHEDDULED_CHANGE_ID = CONVERT(char(255), #SHEDDULED_CHANGE_ID))
MERGE CEQBM AS T
USING CTE S ON T.PRNCPL_ACC_CD = S.PRNCPL_ACC_CD
AND T.BRANCH_ACC_CD = S.BRANCH_ACC_CD
WHEN MATCHED THEN
UPDATE SET
T.[PRNCPL_ACC_CD] = S.[PRNCPL_ACC_CD]
,T.[BRANCH_ACC_CD] = S.[BRANCH_ACC_CD]
,T.[COPY_MISC_DLR_FG] = S.[COPY_MISC_DLR_FG]
,T.[COPY_LABR_HRS_FG] = S.[COPY_LABR_HRS_FG]
,T.[COPY_CSUM_COST_FG] = S.[COPY_CSUM_COST_FG]
,T.[COPY_PART_PRICE_FG] = S.[COPY_PART_PRICE_FG]
,T.[COPY_TRVL_RATE_FG] = S.[COPY_TRVL_RATE_FG]
,T.[COPY_DISC_FG] = S.[COPY_DISC_FG]
,T.[COPY_TAX_RATE_FG] = S.[COPY_TAX_RATE_FG]
,T.[COPY_REJ_RESN_FG] = S.[COPY_REJ_RESN_FG]
,T.[COPY_CNTR_OBLG_FG] = S.[COPY_CNTR_OBLG_FG]
,T.[COPY_LABR_OVRS_FG] = S.[COPY_LABR_OVRS_FG]
WHEN NOT MATCHED THEN
INSERT
( [PRNCPL_ACC_CD]
,[BRANCH_ACC_CD]
,[COPY_MISC_DLR_FG]
,[COPY_LABR_HRS_FG]
,[COPY_CSUM_COST_FG]
,[COPY_PART_PRICE_FG]
,[COPY_TRVL_RATE_FG]
,[COPY_DISC_FG]
,[COPY_TAX_RATE_FG]
,[COPY_REJ_RESN_FG]
,[COPY_CNTR_OBLG_FG]
,[COPY_LABR_OVRS_FG] )
VALUES
(
S.[PRNCPL_ACC_CD]
,S.[BRANCH_ACC_CD]
,S.[COPY_MISC_DLR_FG]
,S.[COPY_LABR_HRS_FG]
,S.[COPY_CSUM_COST_FG]
,S.[COPY_PART_PRICE_FG
,S.[COPY_TRVL_RATE_FG]
,S.[COPY_DISC_FG]
,S.[COPY_TAX_RATE_FG]
,S.[COPY_REJ_RESN_FG]
,S.[COPY_CNTR_OBLG_FG]
,S.[COPY_LABR_OVRS_FG] );
END
-- Using while loop to clean up any records that may have had an issue
-- This should only ever be one record at this stage
WHILE(SELECT TOP 1 * FROM CEQBP WHERE DATE_EXECUTED IS NULL AND EXECUTE_IMMEDIATELY = 1) > 0
BEGIN
DECLARE #UserIdVar VARCHAR(10)
DECLARE #DealerCodeVar VARCHAR(10)
DECLARE #FromBranchVar VARCHAR(10)
WITH CTE AS (SELECT TOP 1 * FROM CEQBP WHERE DATE_EXECUTED IS NULL AND EXECUTE_IMMEDIATELY = 1)
SELECT #UserIdVar = SHEDULED_BY
,#DealerCodeVar = PRNCPL_ACC_CD
,#FromBranchVar = BRANCH_ACC_CD FROM CTE
EXEC sp_CopyData
END
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
DECLARE
#ErrorMessage NVARCHAR(4000),
#ErrorSeverity INT,
#ErrorState INT
SELECT
#ErrorMessage = ERROR_MESSAGE(),
#ErrorSeverity = ERROR_SEVERITY(),
#ErrorState = ERROR_STATE();
END CATCH
END
GO

Datetime field value getting reduced by 1 day while converting XML data into #table values

From my C# application I am getting the XML data as like below
'<NewDataSet>
<tblCFSPFSDDeclaration>
<PKCFSPFSDDeclaration>-1</PKCFSPFSDDeclaration>
<FKCFSPStatus>2</FKCFSPStatus>
<FKBatch>EDCCCL05070801</FKBatch>
<SDWCountSubmitted>112</SDWCountSubmitted>
<SDWCountAccepted>112</SDWCountAccepted>
<CFSPTraderRole>EDCCCL</CFSPTraderRole>
<TurnNo>120220002000</TurnNo>
<CFSPTraderLocation>EDCCCL001</CFSPTraderLocation>
<FSDPeriod>2016-04-01T00:00:00+01:00</FSDPeriod>
</tblCFSPFSDDeclaration>
</NewDataSet>'
You can see that the FSDPeriod is 01/Apr/2016
But when I run the below query after inserting the data into a temporary table I am getting the FSDPeriod value as 31/Mar/2016
DECLARE #ID xml
SET #ID=
'<NewDataSet>
<tblCFSPFSDDeclaration>
<PKCFSPFSDDeclaration>-1</PKCFSPFSDDeclaration>
<FKCFSPStatus>2</FKCFSPStatus>
<FKBatch>EDCCCL05070801</FKBatch>
<SDWCountSubmitted>112</SDWCountSubmitted>
<SDWCountAccepted>112</SDWCountAccepted>
<CFSPTraderRole>EDCCCL</CFSPTraderRole>
<TurnNo>120220002000</TurnNo>
<CFSPTraderLocation>EDCCCL001</CFSPTraderLocation>
<FSDPeriod>2016-04-01T00:00:00+01:00</FSDPeriod>
</tblCFSPFSDDeclaration>
</NewDataSet>'
--2016-05-07T07:49:39+01:00
DECLARE #hDoc int -- handle to the xml document
DECLARE #tblCFSPFSDDeclaration TABLE
(
PKCFSPFSDDeclaration bigint,
FKCFSPStatus int ,
FKBatch varchar(20) ,
ChiefBatchRef varchar(20),
SDWCountSubmitted int ,
SDWCountAccepted int ,
TurnNo varchar(15) ,
CFSPTraderRole varchar(12) ,
CFSPTraderLocation varchar(14) ,
FSDPeriod datetime
)
EXECUTE sp_xml_preparedocument #hDoc output, #ID -- Open the document
INSERT INTO #tblCFSPFSDDeclaration
(
[FKCFSPStatus] ,
[FKBatch] ,
[SDWCountSubmitted] ,
[SDWCountAccepted] ,
[TurnNo] ,
[CFSPTraderRole],
[CFSPTraderLocation],
[FSDPeriod]
)
SELECT [FKCFSPStatus] ,
[FKBatch] ,
[SDWCountSubmitted] ,
[SDWCountAccepted] ,
[TurnNo] ,
[CFSPTraderRole],
[CFSPTraderLocation],
[FSDPeriod]
FROM OPENXML(#hDoc,'/NewDataSet/tblCFSPFSDDeclaration', 2)
WITH
(
[FKCFSPStatus] int ,
[FKBatch] varchar(20) ,
[SDWCountSubmitted] int ,
[SDWCountAccepted] int ,
[TurnNo] varchar(15) ,
[CFSPTraderRole] varchar(12) ,
[CFSPTraderLocation] varchar(14) ,
[FSDPeriod] datetime
)
select * from #tblCFSPFSDDeclaration
Can anyone help to get the data as 01/Apr/2016?
I think this will solve your problem.
Declare the [FSDPeriod] as datetimeoffset.
then you can cast them as you need. If you want only date and time then try this
select Convert(varchar(19), cast([FSDPeriod]as datetime),120) from #tblCFSPFSDDeclaration
for more conversion see here conversion helps
Due to supplied timezone information in the xml, SQL Server normalizes the value to UTC.
2016-04-01T00:00:00+01:00
When you would omit the timezone info, you would see the value you expect.
2016-04-01T00:00:00
Can anyone help to get the data as 01/Apr/2016?
Change [FSDPeriod] datetime to [FSDPeriod] varchar(19) and you will extract the datetime value without the timezone information. That value will be implicitly converted to a datetime when you insert to the table variable.

RDL to SQL, Must declare the scalar variable

I am trying to take a query I found in a RDL file and run it in SQL. I have no idea what I'm doing. I tried multiple solutions I found through searching the web to no avail. The errors I am getting are: "Must declare the scalar variable" for "#locale", "AuthListID", and "UserSIDs". Any suggestions on where to look or how I can fix this? I am very much a SQL n00b. Thank you in advance for any insight.
declare #lcid as int set #lcid = dbo.fn_LShortNameToLCID(CAST (#locale AS varchar(50))
declare #AuthListLocalID as int = case when IsNumeric(#AuthListID)=1 then cast(#AuthListID as int) else (select CI_ID from fn_rbac_AuthListInfo(#lcid,#UserSIDs) where CI_UniqueID=#AuthListID) end
declare #ci table(CI_ID int primary key, CI_UniqueID nvarchar(256), Title nvarchar(512), ArticleID nvarchar(64), BulletinID nvarchar(64), Vendor0 nvarchar(256))
insert #ci
select ui.CI_ID, ui.CI_UniqueID, ui.Title, ui.ArticleID, ui.BulletinID, ven.CategoryInstanceName
from fn_rbac_BundledConfigurationItems(#UserSIDs) bci
join fn_rbac_UpdateInfo(#lcid, #UserSIDs) ui on ui.CI_ID=bci.BundledCI_ID
left join fn_rbac_CICategoryInfo_All(#lcid, #UserSIDs) ven on ven.CI_ID=ui.CI_ID and ven.CategoryTypeName='Company'
where bci.CI_ID=#AuthListLocalID
It seems to me it should look something like this. Hopefully, you have access to all the functions being called, or you might have more digging to do.
DECLARE
#lcid int
, #AuthListLocalID int
, #locale varchar(50)
, #AuthListID int
, #UserSIDs int;
DECLARE #ci TABLE(CI_ID int primary key
, CI_UniqueID nvarchar(256)
, Title nvarchar(512)
, ArticleID nvarchar(64)
, BulletinID nvarchar(64)
, Vendor0 nvarchar(256));
SET #lcid = dbo.fn_LShortNameToLCID(#locale)
SET #AuthListLocalID = CASE
WHEN IsNumeric(#AuthListID)=1
THEN #AuthListID
ELSE (SELECT
CI_ID
FROM fn_rbac_AuthListInfo(#lcid,#UserSIDs)
WHERE CI_UniqueID=#AuthListID)
END
INSERT INTO #ci
VALUES (SELECT
ui.CI_ID
, ui.CI_UniqueID
, ui.Title
, ui.ArticleID
, ui.BulletinID
, ven.CategoryInstanceName
FROM fn_rbac_BundledConfigurationItems(#UserSIDs) bci
INNER JOIN fn_rbac_UpdateInfo(#lcid, #UserSIDs) ui
ON ui.CI_ID=bci.BundledCI_ID
LEFT OUTER JOIN fn_rbac_CICategoryInfo_All(#lcid, #UserSIDs) ven
ON ven.CI_ID=ui.CI_ID
AND ven.CategoryTypeName='Company'
WHERE bci.CI_ID=#AuthListLocalID)

Inserting records in temporary table in sql server?

In SQL Server, I declare one table and trying to insert records, but it is taking so much time to insert. This is my temp table :
declare #totalAprovals Table(
apptype varchar(max)
, Id varchar(max)
, empno varchar(max)
, empname varchar(max)
, AppliedDate varchar(max)
, rstatus varchar(max)
, LeaveType varchar(max)
, fromdate varchar(max)
, todate varchar(max)
, finyear varchar(max)
, noofdays varchar(max)
, perdate varchar(max)
, pertype varchar(max)
, TotMin varchar(max)
, FrmTime varchar(max)
, ToTime varchar(max)
, ConDate varchar(max)
, Amount varchar(max)
, MaterialDesc varchar(max)
, EstValue varchar(max)
, FromYear varchar(max)
, ToYear varchar(max)
, AvailedFrom varchar(max)
, AvailedTo varchar(max)
, Purpose varchar(max)
, FromPlace varchar(max)
, ToPlace varchar(max)
, ICode varchar(max)
, IDesc varchar(max)
, MgrId varchar(max)
)
and my insert statement :
insert into #totalAprovals
SELECT DISTINCT 'LEAVE' AppType
, CRS.applicationId ID
, CRS.EmpId EmpNo
, ISNULL((
SELECT FirstName
FROM Tbl_Emp_M
WHERE EmpId=CRS.EmpId
)
, CRS.EmpId) EmpName
, CONVERT(VARCHAR(10),LA.LeaveDate,103) AppliedDate
, (CASE ISNULL((
SELECT top 1 CurStatus
FROM Tbl_CRS_Leave_AppHis_T
WHERE stepno=CRS.StepNo-1
and applicationId=CRS.applicationId
AND Status=1
order by StepNo desc),'0')
WHEN '0' THEN 'Applied'
WHEN '1' THEN 'Recommended'
WHEN '2' THEN 'Approved'
END) Rstatus
, LT.LeaveName LeaveType
, CONVERT(VARCHAR(10),LA.FromDate,103) FromDate
, CONVERT(VARCHAR(10),LA.ToDate,103) ToDate
, '' FinYear
, '' NoOfDays
, '' PerDate
, '' PerType
, '' TotMin
, '' FrmTime
, '' ToTime
, '' ConDate
, 0 Amount
, '' MaterialDesc
, 0 EstValue
, '' FromYear
, '' ToYear
, ''AvailedFrom
, '' AvailedTo
, '' Purpose
, '' FromPlace
, '' ToPlace
, '' ICode
, '' IDesc
, CRS.MgrId
FROM Tbl_Leave_App_T LA
, Tbl_CRS_Leave_App_T CRS
, Tbl_Leave_Typ_M LT
, Tbl_Emp_ServiceDetails_T EMS
WHERE CRS.applicationId = LA.ApplicationId
AND LA.LeaveTypeId = LT.LeaveTypeId
and crs.EmpId = ems.EmpId
AND CRS.Status = 1
AND LA.Status = 1
AND LT.Status = 1
and ems.Status = 1
AND CRS.CurStatus IN ('0')
AND YEAR(LA.LeaveDate) = YEAR(GETDATE())
AND la.LeaveTypeId not in (9,12)
AND -- LA.ApplicationId LIKE '%LEV%' AND
CRS.EmpId = EMS.EmpId
and ems.LocationCode IN ('101','102','103','104','AHUP')
and crs.MgrId ='xxxxx'
It is taking 2 to 3 minutes to execute this. What could be the reason? Am I writing wrong process to insert records?
You have a performance problem so investigate it as a performance problem. Use a methodology like Waits and Queues. Follow the SQL Server PErformance Flowchart.
When you post here, always add the exact DDL used to create those tables, including all indexes, and capture and link the execution plans.
Most likely is not the INSERT the problem, but the SELECT. DISTINCT is always a code smell indicating a poorly understood join. The WHERE clause is full of non-sargable predicates.
I got the solution, actually i replace the declaring the table like
"declare #totalAprovals Table" to "create table #totalAprovals now it is working superb. Thank you for replying all.