Inserting records in temporary table in sql server? - sql

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.

Related

Creating a decision table with accompanied procedure in SQL Server

I'm trying to think of the best way to write a procedure to evaluate a decision table in SQL Server.
The way I've begun doing it (see VERY simplified example below) would work fine except for the rows where that particular parameter doesn't matter. So, any one claim could fit the scenario in Row 4, provided it's of the type medical.The query, having found a match doesn't even evaluate the other rows. Is there a better way to do this?
I was thinking I could rank the rows of the table from most complicated scenario to least and then select the top row that fits, and that'd probably work, but in future, many more rows will be added to the table and each one would require an analysis of where it would fall in the table. Some situations might even conflict.
I want the best match for the scenario.
I currently have something that does something like this:
create table TTable( RowID varchar(max)
, ClaimType varchar(max)
, Insurance varchar(max)
, Eligibilty varchar(max)
, Result varchar(max)
, Assignment varchar(max)
, Admission varchar(max))
Insert into TTable (RowID, ClaimType, Insurance, Eligibility, Result ,Assignment, Admission)
values ('1' , 'Medical' , 'Insured' , 'Eligible' , 'Approval', 'AssignNurse' , 'Admit')
,('2' , 'Medical' , 'Uninsured' , 'N/A' , 'Denial' , 'N/A' ,'N/A')
,('3' , 'Medical' , 'N/A' , 'IncomeEligible' , 'Pend' , 'AssignReviewer' , 'Pend')
,('4' ,' Medical' , 'N/A' , 'N/A' , 'Pend' , 'Pend' , 'Pend')
create procedure getdecision( #ClaimID uniqueidentifier)
declare #Type
declare #Insurance
declare #Eligibility
Select #Type = Type
From claims
where claimid = #ClaimID
select #Insurance = Insurance
#Eligibility = Eligibility
from MemberInsurance
where membemberid = (select memberid from claims where claimid = #claimid)
select RowID,
Result,
Assignment,
Admission
From ttable t
WHERE #Type = ClaimType
and Case when t.Insurance = 'N/A'
then #Type
Else t.ClaimType
End
and Case when t.Eligible = 'N/A'
then #Eligibility
else t.Eligibilty
end

SQL Server transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements

In the below stored procedure, I'm getting the error mentioned in some cases, what am I doing wrong here?
Error:
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1
Stored procedure:
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].[prcInsDataFeesForVersion]
(#ContractId INT,
#UserId INT,
#VersionNo INT,
#SelectAll BIT,
#SubProductList NVARCHAR(MAX),
#ConvRateFlag BIT)
AS
BEGIN
SET NOCOUNT ON
DECLARE #RetVal INT,
#ErrMsg VARCHAR(255),
#FunctionId INT = 1234,
#AppId VARCHAR(20) = 'ID1021',
#FeesOverrideFlg BIT = 1,
#ContractProdFeeVerSummId INT
CREATE TABLE #tblMasterData
(
ProdCd INT,
ProdName NVARCHAR(255),
SubProdCd INT,
SubProdName NVARCHAR(255),
ProdTypeCd INT,
ProdDeliveryTypCd INT,
ProdStatusCd INT,
ProdStatusDt DATETIME,
CreatedDate DATETIME
)
CREATE TABLE #tblContractInterCulturalDataFiltered
(
ContractID INT
, ContractProdID INT
, ProdCd INT
, ProdName NVARCHAR(255)
, ContractSubProdID INT
, SubProdCd INT
, SubProdName NVARCHAR(255)
, ContractProdStatusCd INT
, ContractProdStatusDt DATETIME
, ContractSubProdStatusCd INT
, ContractSubProdStatusDt DATETIME
, ContractProdFeeId INT
, FeeTypCd INT
, RowMatrixParameterCd INT
, CreatedDate DATETIME
)
CREATE TABLE #tblContractInterCulturalDataFilteredInsert
(
ContractID INT
, ContractProdID INT
, ProdCd INT
, ProdName NVARCHAR(255)
, ContractSubProdID INT
, SubProdCd INT
, SubProdName NVARCHAR(255)
, ContractProdStatusCd INT
, ContractProdStatusDt DATETIME
, ContractSubProdStatusCd INT
, ContractSubProdStatusDt DATETIME
, FeeTypCd INT
, FeeDeterminantCd INT
, RowMatrixParameterCd INT
, ProdFeeCurrCd INT
, RowParameterValueCd INT
, ColumnParameterValueCd INT
, ProdFeePct REAL
, RangeFromDayCnt INT
, RangeToDayCnt INT
, ProdFeeLevelMinAmt DECIMAL
, ProdFeeLevelMaxAmt DECIMAL
, ProdFeeAmt DECIMAL
, ContractProdFeeId INT
, CreatedDate DATETIME
)
CREATE TABLE #tblContractInterCulturalDataFilteredUpdate
(
ContractID INT
, ContractProdID INT
, ProdCd INT
, ProdName NVARCHAR(255)
, ContractSubProdID INT
, SubProdCd INT
, SubProdName NVARCHAR(255)
, ContractProdStatusCd INT
, ContractProdStatusDt DATETIME
, ContractSubProdStatusCd INT
, ContractSubProdStatusDt DATETIME
, FeeTypCd INT
, FeeDeterminantCd INT
, RowMatrixParameterCd INT
, ProdFeeCurrCd INT
, RowParameterValueCd INT
, ColumnParameterValueCd INT
, ProdFeePct REAL
, RangeFromDayCnt INT
, RangeToDayCnt INT
, ProdFeeLevelMinAmt DECIMAL
, ProdFeeLevelMaxAmt DECIMAL
, ProdFeeAmt DECIMAL
, ContractProdFeeId INT
, CreatedDate DATETIME
)
CREATE TABLE #tblSelContractSubProds
(
ContractSubProdId INT
)
BEGIN TRY
BEGIN TRANSACTION
IF(#SelectAll=0 AND #SubProductList IS NOT NULL)
BEGIN
INSERT INTO #tblSelContractSubProds
SELECT intValue FROM dbo.udfSplit(#SubProductList,',',1)
END
INSERT INTO #tblMasterData(
ProdCd
, ProdName
, SubProdCd
, SubProdName
, ProdTypeCd
, ProdDeliveryTypCd
, ProdStatusCd
, ProdStatusDt
, CreatedDate
)
SELECT P.ProdCd
, PC.Descr
, S.SubProdCd
, SC.Descr
, P.ProdTypeCd
, P.ProdDeliveryTypCd
, P.ProdStatusCd
, P.ProdStatusDt
, GETDATE()
FROM tblProduct(NOLOCK) as P
INNER JOIN tblCode(NOLOCK) as PC ON P.ProdCd=PC.Cd and PC.Typ=1053
INNER JOIN tblSubProdDetail(NOLOCK) as S ON P.ProdCd=S.ProdCd
INNER JOIN tblCode(NOLOCK) as SC ON S.SubProdCd=SC.Cd and SC.Typ=1053
WHERE P.ProdDeliveryTypCd=3 and P.ProdStatusCd=1
IF(#SelectAll=1)
BEGIN
INSERT INTO #tblContractInterCulturalDataFiltered(
ContractID
, ContractProdID
, ProdCd
, ProdName
, ContractSubProdID
, SubProdCd
, SubProdName
, ContractProdStatusCd
, ContractProdStatusDt
, ContractSubProdStatusCd
, ContractSubProdStatusDt
, ContractProdFeeId
, FeeTypCd
, RowMatrixParameterCd
, CreatedDate
)
SELECT DISTINCT CP.ContractId,
CP.ContractProdId,
CP.ProdCd,
CPC.Descr,
CSP.ContractSubProdID,
CSP.SubProdCd,
CSPC.Descr,
CP.ContractProdStatusCd,
CP.ContractProdStatusDt,
CSP.ContractSubProdStatusCd,
CSP.ContractSubProdStatusDt,
CPF.ContractProdFeeId,
CPF.FeeTypCd,
CPF.RowMatrixParameterCd,
Getdate()
FROM #tblMasterData(NOLOCK) MD
INNER JOIN tblContractProd(NOLOCK) CP ON MD.ProdCd=CP.ProdCd
INNER JOIN tblContractSubProd(NOLOCK) CSP ON CP.ContractProdId=CSP.ContractProdId
INNER JOIN tblCode(NOLOCK) CPC ON CP.ProdCd=CPC.Cd and CPC.Typ=1053
INNER JOIN tblCode(NOLOCK) CSPC ON CSP.SubProdCd=CSPC.Cd and CSPC.Typ=1053
INNER JOIN tblContractProdFee(NOLOCK) CPF ON CP.ContractProdID=CPF.ContractProdId AND CSP.ContractSubProdID=CPF.ContractSubProdId
WHERE ContractId=#ContractId AND CP.ContractProdStatusCd=1 AND CSP.ContractSubProdStatusCd=1
AND CPF.ContractProdFeeTypStatusCd=1 AND CP.StandardProdIndCd=1 AND CSP.StdSubProdIndCd=1
END
ELSE
BEGIN
IF(#SubProductList IS NOT NULL)
BEGIN
INSERT INTO #tblContractInterCulturalDataFiltered(
ContractID
, ContractProdID
, ProdCd
, ProdName
, ContractSubProdID
, SubProdCd
, SubProdName
, ContractProdStatusCd
, ContractProdStatusDt
, ContractSubProdStatusCd
, ContractSubProdStatusDt
, ContractProdFeeId
, FeeTypCd
, RowMatrixParameterCd
, CreatedDate
)
SELECT DISTINCT CP.ContractId,
CP.ContractProdId,
CP.ProdCd,
CPC.Descr,
CSP.ContractSubProdID,
CSP.SubProdCd,
CSPC.Descr,
CP.ContractProdStatusCd,
CP.ContractProdStatusDt,
CSP.ContractSubProdStatusCd,
CSP.ContractSubProdStatusDt,
CPF.ContractProdFeeId,
CPF.FeeTypCd,
CPF.RowMatrixParameterCd,
Getdate()
FROM #tblMasterData(NOLOCK) MD
INNER JOIN tblContractProd(NOLOCK) CP ON MD.ProdCd=CP.ProdCd
INNER JOIN tblContractSubProd(NOLOCK) CSP ON CP.ContractProdId=CSP.ContractProdId
INNER JOIN tblCode(NOLOCK) CPC ON CP.ProdCd=CPC.Cd and CPC.Typ=1053
INNER JOIN tblCode(NOLOCK) CSPC ON CSP.SubProdCd=CSPC.Cd and CSPC.Typ=1053
INNER JOIN tblContractProdFee(NOLOCK) CPF ON CP.ContractProdID=CPF.ContractProdId AND CSP.ContractSubProdID=CPF.ContractSubProdId
INNER JOIN #tblSelContractSubProds(NOLOCK) SCSP ON CSP.ContractSubProdId=SCSP.ContractSubProdId
WHERE ContractId=#ContractId AND CP.ContractProdStatusCd=1 AND CSP.ContractSubProdStatusCd=1
AND CPF.ContractProdFeeTypStatusCd=1 AND CP.StandardProdIndCd=1 AND CSP.StdSubProdIndCd=1
END
END
INSERT INTO #tblContractInterCulturalDataFilteredUpdate(
ContractID
, ContractProdID
, ProdCd
, ProdName
, ContractSubProdID
, SubProdCd
, SubProdName
, ContractProdStatusCd
, ContractProdStatusDt
, ContractSubProdStatusCd
, ContractSubProdStatusDt
, FeeTypCd
, FeeDeterminantCd
, RowMatrixParameterCd
, ProdFeeCurrCd
, RowParameterValueCd
, ColumnParameterValueCd
, ProdFeePct
, RangeFromDayCnt
, RangeToDayCnt
, ProdFeeLevelMinAmt
, ProdFeeLevelMaxAmt
, ProdFeeAmt
, ContractProdFeeId
, CreatedDate
)
SELECT DISTINCT CICF.ContractId,
CICF.ContractProdId,
CICF.ProdCd,
CICF.ProdName,
CICF.ContractSubProdID,
CICF.SubProdCd,
CICF.SubProdName,
CICF.ContractProdStatusCd,
CICF.ContractProdStatusDt,
CICF.ContractSubProdStatusCd,
CICF.ContractSubProdStatusDt,
CPFM.FeeTypCd,
CPFM.FeeDeterminantCd,
CPFM.RowMatrixParameterCd,
CPFM.ProdFeeCurrCd,
CPFM.RowParameterValueCd,
CPFM.ColumnParameterValueCd,
CPFM.ProdFeePct,
CPFM.RangeFromDayCnt,
CPFM.RangeToDayCnt,
CPFM.ProdFeeLevelMinAmt,
CPFM.ProdFeeLevelMaxAmt,
CPFM.ProdFeeAmt,
CICF.ContractProdFeeId,
Getdate()
FROM #tblContractInterCulturalDataFiltered(NOLOCK) CICF
INNER JOIN tblContractProdFeeMatrix(NOLOCK) CPFM ON CICF.ProdCd=CPFM.FeeMatrixProdCd AND CICF.SubProdCd=CPFM.FeeMatrixSubProdCd AND CICF.FeeTypCd=CPFM.FeeTypCd
INNER JOIN tblContractProdFeeMatrixVersion(NOLOCK) CPFMV ON CPFM.ContractProdFeeMatrixVersionId=CPFMV.ContractProdFeeMatrixVersionId
INNER JOIN tblContractProdFee(NOLOCK) CP ON CICF.ContractProdID=CP.ContractProdId AND CICF.ContractSubProdID=CP.ContractSubProdId AND CICF.ContractProdFeeId=CP.ContractProdFeeId
AND CPFM.FeeDeterminantCd=CP.FeeDeterminantCd AND CPFM.RowMatrixParameterCd =CP.RowMatrixParameterCd
WHERE CICF.ContractId=#ContractId AND CPFMV.ProdFeeMatrixVerNo=#VersionNo AND CICF.ContractProdStatusCd=1 AND CICF.ContractSubProdStatusCd=1 AND CP.ContractProdFeeTypStatusCd=1
AND CPFM.RowMatrixParameterCd IN(6,4)
AND EXISTS(SELECT PFM.ContractProdFeeId from tblProdFeeMatrix(NOLOCK)PFM WHERE CICF.ContractProdFeeId=PFM.ContractProdFeeId)
IF EXISTS(Select 1 From #tblContractInterCulturalDataFilteredUpdate(NOLOCK))
BEGIN
DELETE PFM
FROM tblProdFeeMatrix(NOLOCK) PFM
INNER JOIN #tblContractInterCulturalDataFilteredUpdate(NOLOCK) TIFU ON TIFU.ContractProdFeeId=PFM.ContractProdFeeId
END
INSERT INTO #tblContractInterCulturalDataFilteredInsert(
ContractID
, ContractProdID
, ProdCd
, ProdName
, ContractSubProdID
, SubProdCd
, SubProdName
, ContractProdStatusCd
, ContractProdStatusDt
, ContractSubProdStatusCd
, ContractSubProdStatusDt
, FeeTypCd
, FeeDeterminantCd
, RowMatrixParameterCd
, ProdFeeCurrCd
, RowParameterValueCd
, ColumnParameterValueCd
, ProdFeePct
, RangeFromDayCnt
, RangeToDayCnt
, ProdFeeLevelMinAmt
, ProdFeeLevelMaxAmt
, ProdFeeAmt
, ContractProdFeeId
, CreatedDate
)
SELECT DISTINCT CICF.ContractId,
CICF.ContractProdId,
CICF.ProdCd,
CICF.ProdName,
CICF.ContractSubProdID,
CICF.SubProdCd,
CICF.SubProdName,
CICF.ContractProdStatusCd,
CICF.ContractProdStatusDt,
CICF.ContractSubProdStatusCd,
CICF.ContractSubProdStatusDt,
CPFM.FeeTypCd,
CPFM.FeeDeterminantCd,
CPFM.RowMatrixParameterCd,
CPFM.ProdFeeCurrCd,
CPFM.RowParameterValueCd,
CPFM.ColumnParameterValueCd,
CPFM.ProdFeePct,
CPFM.RangeFromDayCnt,
CPFM.RangeToDayCnt,
CPFM.ProdFeeLevelMinAmt,
CPFM.ProdFeeLevelMaxAmt,
CPFM.ProdFeeAmt,
CICF.ContractProdFeeId,
Getdate()
FROM #tblContractInterCulturalDataFiltered(NOLOCK) CICF
INNER JOIN tblContractProdFeeMatrix(NOLOCK) CPFM ON CICF.ProdCd=CPFM.FeeMatrixProdCd AND CICF.SubProdCd=CPFM.FeeMatrixSubProdCd AND CICF.FeeTypCd=CPFM.FeeTypCd
INNER JOIN tblContractProdFeeMatrixVersion(NOLOCK) CPFMV ON CPFM.ContractProdFeeMatrixVersionId=CPFMV.ContractProdFeeMatrixVersionId
INNER JOIN tblContractProdFee(NOLOCK) CP ON CICF.ContractProdID=CP.ContractProdId AND CICF.ContractSubProdID=CP.ContractSubProdId AND CICF.ContractProdFeeId=CP.ContractProdFeeId
AND CPFM.FeeDeterminantCd=CP.FeeDeterminantCd AND CPFM.RowMatrixParameterCd =CP.RowMatrixParameterCd
WHERE CICF.ContractId=#ContractId AND CPFMV.ProdFeeMatrixVerNo=#VersionNo AND CICF.ContractProdStatusCd=1 AND CICF.ContractSubProdStatusCd=1 AND CP.ContractProdFeeTypStatusCd=1
AND CPFM.RowMatrixParameterCd IN(6,4)
IF EXISTS(Select 1 From #tblContractInterCulturalDataFilteredInsert(NOLOCK))
BEGIN
INSERT INTO [dbo].[tblProdFeeMatrix]
([ContractProdFeeId]
,[ContractBundleFeeId]
,[ContractProdBundleAncilFeeId]
,[RowParameterValueCd]
,[ColumnParameterValueCd]
,[ProdFeeAmt]
,[ProdFeeCurrCd]
,[ProdFeePct]
,[RangeFromDayCnt]
,[RangeToDayCnt]
,[RangeFromPct]
,[RangeToPct]
,[RangeFromAmt]
,[RangeToAmt]
,[ProdFeeLevelMinAmt]
,[ProdFeeLevelMaxAmt]
,[FeeNotApplyIndCd]
,[CreateId]
,[CreateDt]
,[UpdateId]
,[UpdateDt]
,[FunctionId])
SELECT DISTINCT
TIFI.ContractProdFeeID,
0,
0,
TIFI.RowParameterValueCd,
TIFI.ColumnParameterValueCd,
TIFI.ProdFeeAmt,
TIFI.ProdFeeCurrCd,
TIFI.ProdFeePct,
TIFI.RangeFromDayCnt,
TIFI.RangeToDayCnt,
0,
0,
0,
0,
TIFI.ProdFeeLevelMinAmt,
TIFI.ProdFeeLevelMaxAmt,
0,
#UserId,
GETDATE(),
#UserId,
GETDATE(),
#FunctionId
FROM #tblContractInterCulturalDataFilteredInsert(NOLOCK) TIFI
END
IF(#ConvRateFlag=1)
BEGIN
EXEC [ASSET_DB].[dbo].[prcCalculateRates] #UserId,#ContractId,#SelectAll,#SubProductList,#FeesOverrideFlg
END
COMMIT TRANSACTION
SELECT #RetVal=0
GOTO CLEARTEMPTABLES
GOTO DONE
END TRY
BEGIN CATCH
SELECT #ErrMsg = ERROR_PROCEDURE() + ': ' + ERROR_MESSAGE() + ' (Error No. ' + Ltrim(Str(ERROR_NUMBER())) + ') ' + ' at line # ' + Ltrim(Str(ERROR_LINE()))
,#RetVal = 200
GOTO CLEARTEMPTABLES
GOTO ERROR
END CATCH
ERROR:
ROLLBACK TRANSACTION
RAISERROR(#ErrMsg,16,1 )
CLEARTEMPTABLES:
BEGIN TRY
IF EXISTS ( SELECT * FROM tempdb..sysobjects WHERE id = object_id(N'[tempdb]..[#tblMasterData]') )
BEGIN
TRUNCATE TABLE #tblMasterData
DROP TABLE #tblMasterData
END
IF EXISTS ( SELECT * FROM tempdb..sysobjects WHERE id = object_id(N'[tempdb]..[#tblContractInterCulturalDataFiltered]') )
BEGIN
TRUNCATE TABLE #tblContractInterCulturalDataFiltered
DROP TABLE #tblContractInterCulturalDataFiltered
END
IF EXISTS ( SELECT * FROM tempdb..sysobjects WHERE id = object_id(N'[tempdb]..[#tblContractInterCulturalDataFilteredInsert]') )
BEGIN
TRUNCATE TABLE #tblContractInterCulturalDataFilteredInsert
DROP TABLE #tblContractInterCulturalDataFilteredInsert
END
IF EXISTS ( SELECT * FROM tempdb..sysobjects WHERE id = object_id(N'[tempdb]..[#tblContractInterCulturalDataFilteredUpdate]') )
BEGIN
TRUNCATE TABLE #tblContractInterCulturalDataFilteredUpdate
DROP TABLE #tblContractInterCulturalDataFilteredUpdate
END
IF EXISTS ( SELECT * FROM tempdb..sysobjects WHERE id = object_id(N'[tempdb]..[#tblSelContractSubProds]') )
BEGIN
TRUNCATE TABLE #tblSelContractSubProds
DROP TABLE #tblSelContractSubProds
END
END TRY
BEGIN CATCH
SELECT #ErrMsg = ERROR_PROCEDURE() + ': ' + ERROR_MESSAGE() + ' (Error No. ' + Ltrim(Str(ERROR_NUMBER())) + ') ' + ' at line # ' + Ltrim(Str(ERROR_LINE()))
,#RetVal = 201
GOTO ERROR
END CATCH
DONE:
SET NOCOUNT OFF
Return (#RetVal)
END
The fact that lead to this error is that the BEGIN TRANSACTION executed, but neither COMMIT or ROLLBACK did.
The usual reason a stored procedure with a try-transaction block returns that message is the error: table (or other object) not found. This is NOT caught in the try-catch block.
Check the object names exist on runtime.
Also, make sure to run a ROLLBACK manually on the session that spawned this message, if you still haven't fixed the proc.
Documentation:
The following types of errors are not handled by a CATCH block when
they occur at the same level of execution as the TRY...CATCH
construct:
(........)
Object name resolution errors
As you can see, there are also other errors not caught which may be the problem. Check out the possibilities. Many of these error, including the object name resolution, can be caught if you put the procedure CALL inside a try-catch block.
begin try
exec [dbo].[prcInsDataFeesForVersion] ..............
end try
begin catch
SELECT #ErrMsg = ERROR_PROCEDURE() + ': ' + ERROR_MESSAGE() + ' (Error No. ' + Ltrim(Str(ERROR_NUMBER())) + ') ' + ' at line # ' + Ltrim(Str(ERROR_LINE()))
,#RetVal = 201
end catch
This might not sound handy, but at least you can use it to find the error out.

Msg 102, Level 15, State 1, Line 24 Incorrect syntax near '.'

All... based on another question I've posted here recently, I built this stored procedure, but when executed, I receive the error in the title.
As you can see, I tried to remove any aliases, but it didn't matter. Not sure how to use PRINT to see the issue on this either. Of course the isolated SELECT statement works on its own.
I can even pull results from my temp table after the error appears. So is it a problem in this script or the results? Appreciate your assistance. I also only used the WHERE statement to limit the test results.
ALTER PROC ap_vhdr_test AS
SET NOCOUNT ON
IF OBJECT_ID('temp.dbo.#ap_vend_det') is NOT NULL
DROP TABLE #ap_vend_det;
CREATE TABLE #ap_vend_det
(db_name varchar(32)
, vendor_name varchar(40)
, vendor_code varchar(12)
, voucher_no varchar(16)
, invoice_num varchar(16)
, inv_date varchar(16)
, due_date varchar(16)
, apply_date varchar(16)
, total float
, line_desc varchar(40)
, company_id smallint
, gl_num varchar(32)
, acct_site varchar(32)
, sort_code varchar(32)
, nat_gl varchar(32)
, gl_desc varchar(40)
, category nvarchar(510)
, sub_category nvarchar(510)
, po_num varchar(16)
, vendor_class varchar(8)
)
INSERT INTO #ap_vend_det
EXEC sp_MSforeachdb N'IF ''?'' NOT IN ( ''model'',''tempdb'',''master'',''msdb'')
BEGIN SELECT DISTINCT db_name = ''?''
, amaster.addr1 --as vendor_name
, amaster.vendor_code --as vendor_code
, apdet.trx_ctrl_num --as voucher_no
, aphdr.doc_ctrl_num --as invoice_num
, CONVERT(varchar(16),dateadd(dd,(aphdr.date_doc - 639906),''1/1/1753''),101) --as inv_date
, CONVERT(varchar(16),dateadd(dd,(aphdr.date_due - 639906),''1/1/1753''),101) --as due_date
, CONVERT(varchar(16),dateadd(dd,(aphdr.date_applied - 639906),''1/1/1753''),101) --as apply_date
, aphdr.amt_net --as total
, aphdr.doc_desc --as line_desc
, gldet.company_id --as company_id
, gldet.account_code --as gl_num
, gldet.seg2_code --as acct_site
, gldet.seg3_code --as sort_code
, gldet.seg1_code --as nat_gl
, gldet.description --as gl_desc
, ap_coa.group_header --as category
, ap_coa.group_label --as sub_category
, apdet.po_ctrl_num --as po_num
, apvend.vend_class_code --as vendor_class
FROM ?.dbo.amaster --amaster
JOIN ?.dbo.aphdr --aphdr --**
ON amaster.vendor_code = aphdr.vendor_code
AND amaster.pay_to_code = aphdr.pay_to_code
JOIN ?.dbo.apdet --apdet
ON aphdr.trx_ctrl_num = apdet.trx_ctrl_num
JOIN ?.dbo.gldet --gldet
ON aphdr.journal_ctrl_num = gldet.journal_ctrl_num
JOIN ?.dbo.glt --glt
ON gldet.journal_ctrl_num = glt.journal_ctrl_num
JOIN ?.dbo.apvend --apvend
ON amaster.vendor_code = apvend.vendor_code
JOIN reps.dbo.ap_coa --ap_coa
ON gldet.seg1_code = ap_coa.acct_code
WHERE aphdr.date_applied >= ''734785''
END';
SELECT * FROM #ap_vend_det;
This will fail if you have database names that have spaces or other characters in them. You need to enclose them in square brackets, e.g.
FROM [?].dbo.amaster --amaster
Not only that, because you are using 3 part names, you also need to alias the tables in the FROM clause.
FROM [?].dbo.amaster amaster
JOIN [?].dbo.aphdr aphdr --**
ON amaster.vendor_code = aphdr.vendor_code
AND amaster.pay_to_code = aphdr.pay_to_code
JOIN [?].dbo.apdet apdet
ON aphdr.trx_ctrl_num = apdet.trx_ctrl_num
JOIN [?].dbo.gldet gldet
ON aphdr.journal_ctrl_num = gldet.journal_ctrl_num
JOIN [?].dbo.glt glt
ON gldet.journal_ctrl_num = glt.journal_ctrl_num
JOIN [?].dbo.apvend apvend
ON amaster.vendor_code = apvend.vendor_code
JOIN reps.dbo.ap_coa ap_coa
ON gldet.seg1_code = ap_coa.acct_code
WHERE aphdr.date_applied >= ''734785''

Delete and insert on same procedure

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?

i need to use string variable in the Proc in sql server database 2005

I have this procedure
CREATE Proc [dbo].Salse_Ditail
-- Add the parameters for the stored procedure here
#Report_Form varchar(1) ,
#DateFrom datetime ,
#DateTo datetime ,
#COMPANYID varchar(3),
#All varchar(1) ,
#All1 varchar(1) ,
#All2 varchar(1) ,
#All3 varchar(1) ,
#All4 varchar(1) ,
#All5 varchar(1) ,
#Sector varchar(10),
#Report_Parameter nvarchar(max)
as
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
DECLARE #STRWhere nvarchar(max)
IF #All5=0 AND #All4=0 AND #All3=0 AND #All2=0 AND #All1=0 and #All=1
set #STRWhere= N'and Sector_id = #Sector'
if #Report_Form =1 or #Report_Form =3 or #Report_Form =4
SELECT RETURNREASONCODEID, SITE,SITE_NAME,Factory_id,Factory_Name,Sector_id,sector_name,Customer_name,
Customer_id,ITEMID,ITEMNAME,SALESMANID,SALESMAN_NAME,Net_Qty,Net_Salse,Gross_Sales,Gross_Qty,
NETWEIGHT_Gross,NETWEIGHT_salse_Gross,NETWEIGHT_NET,NETWEIGHT_salse_NET,Return_Sales,Free_Good,
CollectionAmount
FROM hal_bas_new_rep
WHERE DATAAREAID =#COMPANYID AND INVOICEDATE >= #DateFrom
AND INVOICEDATE <= #DateTo and Report_Activti = #Report_Form
if #Report_Form =2
SELECT RETURNREASONCODEID , RETURNREASONDESC, SITE , SITE_NAME , Factory_id ,
Factory_Name , Sector_id , sector_name , Customer_name , Customer_id ,
ITEMID , ITEMNAME , SALESMANID , SALESMAN_NAME , Return_Sales
FROM dbo.hal_bas_new_rep
WHERE DATAAREAID =#COMPANYID AND INVOICEDATE >= #DateFrom
AND INVOICEDATE <= #DateTo and Report_Activti = #Report_Form
and RETURNREASONCODEID in
(
SELECT Val
FROM dbo.fn_String_To_Table(#Report_Parameter,',',1)
)
/*
#STRWhere // question: how can I use the variable here?
*/
end
GO
As you see I'm constructing a condition for the WHERE clause in a variable, but I don't know how to use it.
I don't think what you are doing will work. What you need to do is turn the statement that constructs the variable into an appropriate condition and add that to your WHERE clause.
SELECT RETURNREASONCODEID , RETURNREASONDESC, SITE , SITE_NAME , Factory_id ,
Factory_Name , Sector_id , sector_name , Customer_name , Customer_id ,
ITEMID , ITEMNAME , SALESMANID , SALESMAN_NAME , Return_Sales
FROM dbo.hal_bas_new_rep
WHERE DATAAREAID =#COMPANYID AND INVOICEDATE >= #DateFrom
AND INVOICEDATE <= #DateTo and Report_Activti = #Report_Form
AND RETURNREASONCODEID in
(
SELECT Val
FROM dbo.fn_String_To_Table(#Report_Parameter,',',1)
)
AND (NOT(#All5=0 AND #All4=0 AND #All3=0 AND #All2=0 AND #All1=0 AND #All=1)
OR Sector_id = #Sector)
You can build all your query in the variable and use EXECUTE to get the result.
Is orrible but work