I have the following statement inside a stored procedure:
INSERT INTO #tblThreatenedSpeciesSubzone
(ThreatenedSpeciesZoneID,
ManagementZoneID,
VegetationZoneID)
SELECT *
FROM OPENXML (#hDoc, '/NewDataSet/tblThreatenedSpeciesSubzone', 2)
WITH (ThreatenedSpeciesZoneID INT,
ManagementZoneID INT,
VegetationZoneID INT) XMLDATA
WHERE VegetationZoneID = #VegetationZoneIDInXML
Sometime "managementZone id" becomes null, I want to replace if it is null then I want pass the constant value "0". Is there a way to do ?
Not sure about "passing a constant value", but you can always set a default:
CREATE PROCEDURE Sales.uspGetSalesYTD
#SalesPerson nvarchar(50) = 'Andersson' -- default value
AS
So:
#ManagementZoneID INT = 0
You could use a coalesce in the select statement
INSERT INTO #tblThreatenedSpeciesSubzone
( ThreatenedSpeciesZoneID ,
ManagementZoneID ,
VegetationZoneID
)
SELECT
ThreatenedSpeciesZoneID ,
COALESCE(ManagementZoneID,0) ,
VegetationZoneID
FROM OPENXML (#hDoc, '/NewDataSet/tblThreatenedSpeciesSubzone', 2)
WITH ( ThreatenedSpeciesZoneID INT ,
ManagementZoneID INT ,
VegetationZoneID INT ) XMLDATA
WHERE VegetationZoneID = #VegetationZoneIDInXML
Related
I am new to SQL and trying to determine how to set a variable to either A or B.
Here is the statement:
DECLARE #Planner AS VARCHAR(50) = '2566927' OR #Planner = '12201704'
And the error I am receiving:
The following errors occurred during execution of the SQL query:
Incorrect syntax near the keyword 'OR'.
Here is a more complete sample:
DECLARE
#Planner AS VARCHAR(50) = '2566927'
--Temp Table for Final
CREATE TABLE #PP1(
Part_Key varChar(50)
,Part_No varChar(50)
,Part_Name varChar(50)
,CurInv DECIMAL(10,2)
,MinInv DECIMAL(10,2)
,Past_Due DECIMAL(10,2)
,Week2 DECIMAL(10,2)
,Week4 DECIMAL(10,2)
,Week8 DECIMAL(10,2)
,Week12 DECIMAL(10,2)
,Plus12 DECIMAL(10,2)
,Dep26w DECIMAL(10,1)
,Stock DECIMAL(10,1)
,StockPur DECIMAL (10,1)
)
--Temp Table to Limit Parts
CREATE TABLE #MRP_Parts(
MRP_PK varChar(50)
,MRP_PN varChar(50)
,MRP_PNAME varChar(50)
)
--Insert into Temp Part Table
INSERT #MRP_Parts
SELECT
PP.Part_Key
,PP.Part_No
,PP.Name
FROM Part_v_Part AS PP
WHERE (PP.Planner = #Planner OR #Planner = '')
--BEGIN Temp Table for Inventory
CREATE TABLE #CurrInv(
CI_Part_Key varChar(50)
,CI_Part_No varChar(50)
,CI_Qty DECIMAL(10,1)
,CI_Min DECIMAL(10,2)
)
INSERT #CurrInv
SELECT
PP.PArt_Key
,PP.Part_No
,ISNULL(PC1.Quantity,0)
,PP.Minimum_Inventory_Quantity
FROM Part_v_Part AS PP
OUTER APPLY
(
SELECT
SUM(PC.Quantity) AS Quantity
FROM Part_v_Container as PC
WHERE PP.part_Key=PC.part_Key
AND (PC.Container_Status = 'OK'
OR PC.Container_Status = 'Receiving'
OR PC.Container_Status = 'Testing Hold')
AND PC.Active = '1'
AND (PP.Planner = #Planner OR #Planner = '')
) AS PC1
What I would like is for the #Planner to be either A or B
A second variable must have a different name. E.g.
DECLARE #Planner1 VARCHAR(50) = '2566927',
#Planner2 varchar(10) = '12201704',
#OtherVar int = 42
And separate each variable declaration with a comma ,
You can't do that, but you can declare a variable as a table and put multiple values into the table
DECLARE #Planner AS TABLE (P VARCHAR(50))
INSERT #Planner SELECT '2566927'
INSERT #Planner SELECT '12201704'
And then you can use the table variable in a where in type clause
SELECT
PP.Part_Key
,PP.Part_No
,PP.Name
FROM Part_v_Part AS PP
WHERE PP.Planner IN (SELECT P FROM #Planner)
I am reading a text file as an input to execute the logic in my stored procedure following is the sample of my textfile
<tblThreatenedSpeciesSubzone>
<ThreatenedSpeciesZoneID>-1</ThreatenedSpeciesZoneID>
<ManagementZoneID>0</ManagementZoneID>
<TSSubZoneNumber>BR101_Moderate/Good_Medium_1</TSSubZoneNumber>
<TSSubZoneArea>0</TSSubZoneArea>
<AdjacentRemnantVegArea>23</AdjacentRemnantVegArea>
<PatchArea>0</PatchArea>
<CreatedBySystemUser>BBCC Training 1</CreatedBySystemUser>
<UpdatedBySystemUser>BBCC Training 1</UpdatedBySystemUser>
<SaveType>1</SaveType>
<VegetationZoneID>-1</VegetationZoneID>
<ManagementZoneName />
</tblThreatenedSpeciesSubzone>
If you noticed <ManagementZoneName /> don't have any value. In my stored procedure I tried to find if Managementzone has value or not but not sure is the right way to do
IF #ManagementZoneIDInXML > 0 and ##ManagementZoneIDInXML <> NULL
BEGIN
INSERT INTO #tblThreatenedSpeciesSubzone
(ThreatenedSpeciesZoneID,
ManagementZoneID,
VegetationZoneID,
TSSubZoneNumber,
TSSubZoneArea,
AdjacentRemnantVegArea,
PatchArea,
DateCreated,
CreatedBySystemUser,
DateUpdated,
UpdatedBySystemUser,
SaveType,
RowTimestamp)
SELECT *
FROM OPENXML (#hDoc, '/NewDataSet/tblThreatenedSpeciesSubzone', 2)
WITH (ThreatenedSpeciesZoneID INT,
ManagementZoneID INT,
VegetationZoneID INT,
TSSubZoneNumber VARCHAR(50),
TSSubZoneArea NUMERIC(9,2),
AdjacentRemnantVegArea NUMERIC(9,2),
PatchArea NUMERIC(9,2),
DateCreated VARCHAR(50),
CreatedBySystemUser VARCHAR(50),
DateUpdated VARCHAR(50),
UpdatedBySystemUser VARCHAR(50),
SaveType INT,
RowTimestamp VARCHAR(50)) XMLDATA
WHERE
ManagementZoneID = #ManagementZoneIDInXML --Only select the rows that belong to the supplied ManagementZoneID
END
ELSE
BEGIN
INSERT INTO #tblThreatenedSpeciesSubzone
( ThreatenedSpeciesZoneID ,
ManagementZoneID ,
VegetationZoneID ,
TSSubZoneNumber ,
TSSubZoneArea ,
AdjacentRemnantVegArea ,
PatchArea ,
DateCreated ,
CreatedBySystemUser ,
DateUpdated ,
UpdatedBySystemUser ,
SaveType ,
RowTimestamp )
SELECT * FROM OPENXML (#hDoc, '/NewDataSet/tblThreatenedSpeciesSubzone', 2)
WITH ( ThreatenedSpeciesZoneID INT ,
ManagementZoneID INT ,
VegetationZoneID INT ,
TSSubZoneNumber VARCHAR(50) ,
TSSubZoneArea NUMERIC(9,2) ,
AdjacentRemnantVegArea NUMERIC(9,2) ,
PatchArea NUMERIC(9,2) ,
DateCreated VARCHAR(50) ,
CreatedBySystemUser VARCHAR(50) ,
DateUpdated VARCHAR(50) ,
UpdatedBySystemUser VARCHAR(50) ,
SaveType INT ,
RowTimestamp VARCHAR(50) ) XMLDATA
WHERE VegetationZoneID = #VegetationZoneIDInXML --Only select the rows that belong to the supplied VegetationZoneID
--And no Management zone assigned
END
CREATE TYPE [dbo].[JNLOBJLIST] AS TABLE(
[Journal_Master_Id] [int] NULL,
[strTransRefNumber] [varchar](50) NULL,
[dateGLTransDate] [date] NULL,
[decGLTransAmount] [decimal](18, 4) NULL,
[strGLTransRemark] [varchar](50) NULL,
[guidCompanybranchId] [uniqueidentifier] NULL,
[intGLAccountId] [int] NULL,
[intFiscalYearId] [int] NULL,
[boolGLIsDebit] [binary](1) NULL,
[strPerson] [varchar](50) NULL,
[inttblReferenceId] [int] NULL,
[decGLTransAmount2] [decimal](18, 4) NULL,
[strJournalmemo] [varchar](50) NULL)
GO
and SP:
CREATE PROCEDURE [dbo].[usp_insertGl_transtemp2]
#LIST [dbo].JNLOBJLIST READONLY
AS
DECLARE #id int
BEGIN
INSERT INTO tbl_GL_Trans_Detailstemp
( trans_ref_number
, GL_trans_date
, GL_trans_amount
, GL_trans_remark
, company_branch_id
, GL_Account_id
, fiscal_year_id
, IsDebit
, Person
, tbl_reference_Id)
SELECT strTransRefNumber
, dateGLTransDate
, decGLTransAmount
, strGLTransRemark
, guidCompanybranchId
, intGLAccountId
, intFiscalYearId
, boolGLIsDebit
, strPerson
, inttblReferenceId FROM #LIST
SET #id = (SELECT MAX(GL_trans_id)
FROM tbl_GL_Trans_Detailstemp)
UPDATE tbl_Gl_account
SET GL_Balance = GL_Balance + (SELECT decGLTransAmount2 FROM #LIST)
WHERE (GL_Account_id = (SELECT intGLAccountId FROM #LIST))
DECLARE #Journal_Master_Id int
DECLARE #Trans_Id int
DECLARE #Amount decimal
DECLARE #Memo varchar(50)
SET #Journal_Master_Id=(SELECT Journal_Master_Id FROM #LIST)
SET #Trans_Id=(#id)
SET #Amount=(SELECT decGLTransAmount FROM #LIST)
SET #Memo=(SELECT strJournalmemo FROM #LIST)
INSERT INTO tbl_Journal_Details
(Journal_Master_Id, Trans_Id, Amount, Memo)
VALUES (#Journal_Master_Id,#Trans_Id,#Amount,#Memo)
END
RETURN
actually after my first insert statement , i need the value of tbl_GL_Trans_Detailstemp's
primary key GL_trans_id to insert it into next table...
So if the type table #LIST has many rows(say 5), i need all the statements to get executed one by one(as a loop works)
But as far i have checked the first insert statement works as a whole at first, then only next statements get excecuted. How can i overcome this?
To be more precise, i need a solution which uses following logic
CREATE PROCEDURE [dbo].[usp_insertGl_transtemp2]
#LIST [dbo].JNLOBJLIST READONLY,
#COUNT int
AS
DECLARE #id int
DECLARE #rowcount int=0
WHILE #rowcount<#COUNT
BEGIN
INSERT INTO tbl_GL_Trans_Detailstemp
( trans_ref_number
, GL_trans_date
, GL_trans_amount
, GL_trans_remark
, company_branch_id
, GL_Account_id
, fiscal_year_id
, IsDebit
, Person
, tbl_reference_Id)
SELECT #rowcount.strTransRefNumber
, #rowcount.dateGLTransDate
, #rowcount.decGLTransAmount
, #rowcount.strGLTransRemark
, #rowcount.guidCompanybranchId
, #rowcount.intGLAccountId
, #rowcount.intFiscalYearId
, #rowcount.boolGLIsDebit
, #rowcount.strPerson
, #rowcount.inttblReferenceId FROM #LIST
SET #id = (SELECT MAX(GL_trans_id)
FROM tbl_GL_Trans_Detailstemp)
UPDATE tbl_Gl_account
SET GL_Balance = GL_Balance + (SELECT #rowcount.decGLTransAmount2 FROM #LIST)
WHERE (GL_Account_id = (SELECT #rowcount.intGLAccountId FROM #LIST))
DECLARE #Journal_Master_Id int
DECLARE #Trans_Id int
DECLARE #Amount decimal
DECLARE #Memo varchar(50)
SET #Journal_Master_Id=(SELECT #rowcount.Journal_Master_Id FROM #LIST)
SET #Trans_Id=(#id)
SET #Amount=(SELECT #rowcount.decGLTransAmount FROM #LIST)
SET #Memo=(SELECT #rowcount.strJournalmemo FROM #LIST)
INSERT INTO tbl_Journal_Details
(Journal_Master_Id, Trans_Id, Amount, Memo)
VALUES (#Journal_Master_Id,#Trans_Id,#Amount,#Memo)
SET #rowcount = #rowcount + 1
END
RETURN
It may be possible to avoid a loop and use the OUTPUT from the first INSERT later on in the query. The example below is based on a guess that #list.strTransRefNumber is UNIQUE. Even if it's not UNIQUE it may still be possible for you to refactor the JOIN in the last INSERT as you know how things are related etc.
CREATE PROCEDURE [dbo].[usp_insertGl_transtemp2]
#list [dbo].JNLOBJLIST READONLY
AS
BEGIN
BEGIN TRAN
DECLARE #inserted TABLE ( id INT NOT NULL, strTransRefNumber VARCHAR(50) NOT NULL )
INSERT INTO tbl_GL_Trans_Detailstemp
( trans_ref_number, GL_trans_date, GL_trans_amount, GL_trans_remark, company_branch_id
, GL_Account_id, fiscal_year_id, IsDebit, Person, tbl_reference_Id )
OUTPUT INSERTED.GL_trans_id, INSERTED.trans_ref_number INTO #inserted
SELECT strTransRefNumber, dateGLTransDate, decGLTransAmount, strGLTransRemark
, guidCompanybranchId, intGLAccountId, intFiscalYearId, boolGLIsDebit
, strPerson, inttblReferenceId
FROM #list
-- refactored it to use a join which i think is what you need here
UPDATE a
SET a.GL_Balance = a.GL_Balance + l.decGLTransAmount2
FROM tbl_Gl_account a
JOIN #list l ON l.intGLAccountId = a.GL_Account_id
INSERT INTO tbl_Journal_Details
(Journal_Master_Id, Trans_Id, Amount, Memo)
SELECT l.Journal_Master_Id, i.id, l.decGLTransAmount, l.strJournalmemo
FROM #list l
JOIN #inserted i ON i.strTransRefNumber = l.strTransRefNumber
COMMIT
END
RETURN
I have a stored procedure that inserts data on a table with an auto-increment id (name of 'requestid'). As I insert data into it using the procedure, I want to take the value of the auto-increment field and use it on another query to the same stored procedure. How do I do that? Thank you in advance for your time.
CREATE PROCEDURE [dbo].[sp_Create_new_request]
#employeeid INT ,
#requestdate DATETIME ,
#deliverdate DATETIME ,
#totalcost MONEY
AS
BEGIN
INSERT INTO dbo.Requests
(
EmployeeID ,
RequestDate ,
DeliverDate ,
TotalCost
)
VALUES
(
#employeeid ,
#requestdate ,
#deliverdate ,
#totalcost
)
END
Try
CREATE PROCEDURE [dbo].[sp_Create_new_request]
#employeeid INT ,
#requestdate DATETIME ,
#deliverdate DATETIME ,
#totalcost MONEY,
requestid INT = NULL OUT
AS
BEGIN
INSERT INTO dbo.Requests
(
EmployeeID ,
RequestDate ,
DeliverDate ,
TotalCost
)
VALUES
(
#employeeid ,
#requestdate ,
#deliverdate ,
#totalcost
)
SET #requestid = SCOPE_IDENTITY();
END
You should not use auto increment instead use sequence to increment and then you can reuse that value anywhere.
You can use also :
IDENT_CURRENT ('dbo.Requests')
Information about IDENT_CURRENT
http://technet.microsoft.com/en-us/library/ms175098.aspx
I am trying to update a data set based on one conditional and then retrieving all the updated rows. VS keeps telling me there is an incorrect syntax error near my OUTPUT clause but I do not see anything wrong. I am just trying to figure out how to use "OUTPUT" so this may be a very stupid mistake I am making but failing to see.
What is wrong (syntactically) with this OUTPUT clause?
CREATE PROCEDURE [dbo].[GetInitialSessionNotifications]
#CurrentSessionId bigint
AS
DECLARE #tempTable table(
id bigint NOT NULL,
[Type] nvarchar,
DocumentCommentID bigint,
AnnouncmentID int,
EventID int,
MeetingID int,
[Read] bit,
RecieverId int,
AnnouncmentCommentId bigint,
EventCommentId bigint,
MeetingCommentId bigint,
DateAndTime DateTime);
UPDATE Notifications SET SessionId = #CurrentSessionId
WHERE SessionId != #CurrentSessionId
OUTPUT INSERTED.id,
INSERTED.[Type],
INSERTED.DocumentCommentID,
INSERTED.AnnouncmentID,
INSERTED.EventID,
INSERTED.MeetingID,
INSERTED.[Read],
INSERTED.RecieverId,
INSERTED.AnnouncmentCommentId,
INSERTED.EventCommentId,
INSERTED.MeetingCommentId,
INSERTED.DateAndTime
INTO #tempTable;
SELECT id, [Type], DocumentCommentId, AnnouncmentID, EventID, MeetingID,
[Read], RecieverId, AnnouncmentCommentId, EventCommentId, MeetingCommentId, DateAndTime
FROM #tempTable;
RETURN 0
Try this one -
CREATE PROCEDURE [dbo].[GetInitialSessionNotifications]
#CurrentSessionId BIGINT
AS BEGIN
DECLARE #tempTable TABLE
(
id BIGINT NOT NULL ,
[Type] NVARCHAR ,
DocumentCommentID BIGINT ,
AnnouncmentID INT ,
EventID INT ,
MeetingID INT ,
[Read] BIT ,
RecieverId INT ,
AnnouncmentCommentId BIGINT ,
EventCommentId BIGINT ,
MeetingCommentId BIGINT ,
DateAndTime DATETIME
)
UPDATE Notifications
SET SessionId = #CurrentSessionId
OUTPUT
INSERTED.id ,
INSERTED.[Type] ,
INSERTED.DocumentCommentID ,
INSERTED.AnnouncmentID ,
INSERTED.EventID ,
INSERTED.MeetingID ,
INSERTED.[Read] ,
INSERTED.RecieverId ,
INSERTED.AnnouncmentCommentId ,
INSERTED.EventCommentId ,
INSERTED.MeetingCommentId ,
INSERTED.DateAndTime
INTO #tempTable
WHERE SessionId != #CurrentSessionId
SELECT id ,
[Type] ,
DocumentCommentId ,
AnnouncmentID ,
EventID ,
MeetingID ,
[Read] ,
RecieverId ,
AnnouncmentCommentId ,
EventCommentId ,
MeetingCommentId ,
DateAndTime
FROM #tempTable;
END