Using case to delete data row - sql

I created a simple stored procedure to update my table, but currently what I need is
Delete * from [ABCSystem].[dbo].[NEW_TEST_NUMBER]
WHERE sONbr = #sONbr AND SOLine = #SOLine
If #Statuscode is = "N001" by using case. Anyone can show me a simple sample or something?
Thank you.
ALTER PROCEDURE [dbo].[usp_Testing]
-- Add the parameters for the stored procedure here
#sONbr nvarchar(50) = NULL,
#SOLine nvarchar(50) = NULL,
#SerialNbr nvarchar(50) = NULL,
#StatusCode nvarchar(50) = NULL,
#PackType nvarchar(50) = NULL,
#PalletID nvarchar(50) = NULL,
#PackingListNo nvarchar(50) = NULL,
#CrDateTime nvarchar(50) = NULL,
#CrUserID nvarchar(50) = NULL,
#return nvarchar(50) = NULL OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
IF EXISTS(
SELECT sONbr , SOLine
FROM [ABCSystem].[dbo].[NEW_TEST_NUMBER]
WHERE sONbr = #sONbr AND SOLine = #SOLine
)
BEGIN
UPDATE [ABCSystem].[dbo].[NEW_TEST_NUMBER]
SET StatusCode = #StatusCode
,LastUpdDateTime = GETDATE()
,LastUpdUserID = #CrUserID
,StatusDesc =
CASE #StatusCode WHEN 'N001' THEN 'New'
WHEN 'PR001' THEN 'Prepack In Progress'
WHEN 'PR002' THEN 'PrePacking Completed'
WHEN 'WE002' THEN 'Weight Complete'
END
,PalletID =
CASE #StatusCode WHEN 'N001' THEN cast(null as nvarchar(50))
ELSE PalletID
END
,PackType =
CASE #StatusCode WHEN 'N001' THEN cast(null as nvarchar(50))
ELSE PackType
END
,JobID =
CASE #StatusCode WHEN 'N001' THEN cast(null as nvarchar(50))
ELSE JobID
END
,JobCrDateTime =
CASE #StatusCode WHEN 'N001' THEN cast(null as nvarchar(50))
ELSE JobCrDateTime
END
,PackingListNo =
CASE #StatusCode WHEN 'N001' THEN cast(null as nvarchar(50))
ELSE PackingListNo
END
WHERE sONbr = #sONbr AND SOLine = #SOLine
IF ##ERROR <> 0
Set #Return = 'UPDATE FAILED!'
ELSE
Set #Return = 'UPDATE SUCCESSFULLY.'
END
ELSE
BEGIN
Set #Return = 'NO DATA EXIST!'
END

As far as I am seing your problem, you have to create a simple table that will tell you INSERT, UPDATE, DELETE. Link the table inside your stored proc. This will help you to sort things down.
OR
Simply sort everything in loop inside stored proc telling that
WHEN #StatusCode = 'N001'
DO update
ELSE
DO something else

Related

Stored procedure with OUTPUT - Must declare the scalar variable

I'm writing a stored procedure that will be executed from C# to get data from database. Therefore I have to pass a GUID to this stored procedure and it should find data in table Contact or in the Lead table & return data back to C# app via output parameters.
When I try to execute this stored procedure in SSMS, I get a SQL exception
Must declare the scalar variable "#LastName"
Code:
ALTER PROCEDURE [api].[GetUser_NetId]
#NetId uniqueidentifier
, #LastName nvarchar(200) = '' OUTPUT
, #FirstName nvarchar(200) = '' OUTPUT
, #Country uniqueidentifier = NULL OUTPUT
, #Newsletter bit = 0 OUTPUT
AS
DECLARE
#Table SMALLINT
SET #Table = (
SELECT MIN(T.ID) FROM (
SELECT 100 AS [ID] FROM dbo.Contact WHERE Net_ID = #NetId
UNION ALL
SELECT 200 AS [ID] FROM dbo.Lead WHERE Net_ID = #NetId
) T
)
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = CONCAT(
' SELECT
#LastName = tbl.LastName,
#FirstName = tbl.FirstName,
#Country = tbl.Address1CountryId,
#Newsletter = tbl.Newsletter,
FROM
dbo.'
, CASE #Table
WHEN 100 THEN 'Contact'
WHEN 200 THEN 'Lead'
END
, ' as tbl
WHERE 1=1
AND tbl.Net_Id = '''
, #NetId
, ''''
)
EXEC(#SQL)
..a slightly simpler approach
ALTER PROCEDURE [api].[GetUser_NetId]
#NetId uniqueidentifier
, #LastName nvarchar(200) = '' OUTPUT
, #FirstName nvarchar(200) = '' OUTPUT
, #Country uniqueidentifier = NULL OUTPUT
, #Newsletter bit = 0 OUTPUT
AS
BEGIN
IF EXISTS(SELECT * FROM dbo.Contact WHERE Net_ID = #NetId)
BEGIN
SELECT
#LastName = tbl.LastName,
#FirstName = tbl.FirstName,
#Country = tbl.Address1CountryId,
#Newsletter = tbl.Newsletter
FROM dbo.Contact WHERE Net_ID = #NetId;
END
ELSE
BEGIN
SELECT
#LastName = tbl.LastName,
#FirstName = tbl.FirstName,
#Country = tbl.Address1CountryId,
#Newsletter = tbl.Newsletter
FROM dbo.Lead WHERE Net_ID = #NetId;
END
END
I am getting an error like:
Msg 137, Level 15, State 2, Line 18
Must declare the scalar variable "#CustomerKey".
Msg 137, Level 15, State 1, Line 21
Must declare the scalar variable "#FirstName".
Msg 137, Level 15, State 1, Line 30
Must declare the scalar variable "#FirstName".
IF EXISTS(SELECT * FROM VW_FactInternetSales WHERE CustomerKey = #CustomerKey)
BEGIN
SELECT
#FirstName = .FirstName,
#TaxAmt = .TaxAmt,
#Country = .Country,
#CustomerKey = .CustomerKey
FROM DimCustomer WHERE CustomerKey = #CustomerKey
END
ELSE
BEGIN
SELECT
#FirstName = .FirstName,
#TaxAmt = .TaxAmt,
#Country = .Country,
#CustomerKey = .CustomerKey
FROM VW_FactInternetSales WHERE CustomerKey = #CustomerKey
END
END
I cant add my table in this line
#FirstName = .FirstName,
#TaxAmt = .TaxAmt,
#Country = .Country,
#CustomerKey = .CustomerKey

Sql Scope_Identity() return Null?

I am facing this issue that my stored proc always return NULL though i have set my #output variable as well.I want to get last inserted scope Id from the table.
can someone help me where i have got wrong?
ALTER PROC spAddOrUpdateMember
#pMemberId INT = 0 ,
#pFirstName VARCHAR(50) = 'aa',
#pLastName VARCHAR(50)='aa' ,
#pMemberCode VARCHAR(15) = '12312',
#pDOB DATE = '03/10/2019',
#pGrade INT = 2 ,
#pCNIC VARCHAR(14) = '3423434',
#pFatherName VARCHAR(50) = 'asdasd' ,
#pCurrentAddress VARCHAR(MAX) = 'asds' ,
#pPermanentAddress VARCHAR(MAX) = 'fgdf',
#pEmploymentAddress VARCHAR(MAX) = 'ytuyu' ,
#pNationality INT =2
#output int = 0 output
AS
BEGIN
IF #pMemberId > 0
BEGIN
---UPDATE ME
UPDATE [dbo].[QC_Member_Profile]
SET
[FirstName] = #pFirstName
,[LastName] = #pLastName
,[DOB] = #pDOB
,[CNIC] = #pCNIC
,[FatherName] = #pFatherName
,[CurrentAddress] = #pCurrentAddress
,[PermanentAddress] = #pPermanentAddress
,[Nationality] = #pNationality
,[MemberTypeId] =#pMemberTypeId
WHERE MemberId = #pMemberId
END
ELSE
BEGIN
---INSERT ME
INSERT INTO QC_Member_Profile VALUES(
dbo.PIdentityKey(0),
#pFirstName,
#pLastName,
#pDOB,
#pCNIC,
#pFatherName,
#pCurrentAddress,
#pPermanentAddress,
#pNationality,
)
set #output = SCOPE_IDENTITY();
SELECT #output = SCOPE_IDENTITY();
select #output
END
END
I've guessed the name of your ID column, however, this should work. You'll need to amend the name of your ID column if it isn't called MemberID or if it doesn't have the data type int:
ALTER PROC spAddOrUpdateMember #pMemberId int = 0,
#pFirstName varchar(50) = 'aa',
#pLastName varchar(50) = 'aa',
#pMemberCode varchar(15) = '12312',
#pDOB date = '03/10/2019',
#pGrade int = 2,
#pCNIC varchar(14) = '3423434',
#pFatherName varchar(50) = 'asdasd',
#pCurrentAddress varchar(MAX) = 'asds',
#pPermanentAddress varchar(MAX) = 'fgdf',
#pEmploymentAddress varchar(MAX) = 'ytuyu',
#pNationality int = 2,
#output int = 0 OUTPUT
AS
BEGIN
IF #pMemberId > 0
BEGIN
UPDATE [dbo].[QC_Member_Profile]
SET [FirstName] = #pFirstName,
[LastName] = #pLastName,
[DOB] = #pDOB,
[CNIC] = #pCNIC,
[FatherName] = #pFatherName,
[CurrentAddress] = #pCurrentAddress,
[PermanentAddress] = #pPermanentAddress,
[Nationality] = #pNationality,
[MemberTypeId] = #pMemberTypeId
WHERE MemberId = #pMemberId;
END;
ELSE
BEGIN
DECLARE #ins table (OutputID int);
INSERT INTO QC_Member_Profile
OUTPUT Inserted.MemberID --guessed name
INTO #Ins
VALUES (dbo.PIdentityKey(0), #pFirstName, #pLastName, #pDOB, #pCNIC, #pFatherName, #pCurrentAddress, #pPermanentAddress, #pNationality);
SELECT #output = OutputID
FROM #ins;
SELECT #Output;
END;
END;
I've also fixed the syntax errors that were in your original question.

How to run stored procedure query between 2 table & insert data base on reference column?

I've created a simple stored procedure to update my Sample_TAG_NUMBERTEST table but I need it to get an ItemCode from another table PartItem by using both SOLine & SONbr to do the query but I don't know how to write it.
2nd thing I need to do is when my StatusCode column is N001 then my DESC column will automatically insert NEW ORDER data value, for PR002 my DESC column will become Progress.
How can I do that? Thanks in advance.
ALTER PROCEDURE [dbo].[SampleTagNumberUpdate]
#sONbr nvarchar(50) = NULL,
#SOLine nvarchar(50) = NULL,
#SerialNbr nvarchar(50) = NULL,
#StatusCode nvarchar(50) = NULL,
#PackType nvarchar(50) = NULL,
#PalletID nvarchar(50) = NULL,
#PackingListNo nvarchar(50) = NULL,
#ItemCode nvarchar(50) = NULL,
#CrDateTime nvarchar(50) = NULL,
#CrUserID nvarchar(50) = NULL,
#return nvarchar(50) = NULL OUTPUT
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT sONbr , SOLine
FROM [SampleSystem].[dbo].[Sample_TAG_NUMBERTEST]
WHERE sONbr = #sONbr AND SOLine = #SOLine)
BEGIN
UPDATE [SampleSystem].[dbo].[Sample_TAG_NUMBERTEST]
SET SerialNbr = #SerialNbr
,StatusCode = #StatusCode
,PackType = #PackType
,PalletID = #PalletID
,PackingListNo = #PackingListNo
,ItemCode = #ItemCode
,LastUpdDateTime = GETDATE()
,LastUpdUserID = #CrUserID
WHERE sONbr = #sONbr AND SOLine = #SOLine
IF ##ERROR <> 0
Set #Return = 'UPDATE FAILED'
ELSE
Set #Return = 'UPDATE SUCCESSFULLY'
END
ELSE
BEGIN
INSERT INTO [SampleSystem].[dbo].[Sample_TAG_NUMBERTEST](SONbr, SOLine, SerialNbr
,StatusCode
,PackType
,PalletID
,PackingListNo
,ItemCode
,CrDateTime
,CrUserID)
VALUES(#sONbr, #SOLine, #SerialNbr, #StatusCode, #PackType
,#PalletID
,#PackingListNo
,#ItemCode
,GETDATE()
,#CrUserID)
IF ##ERROR <> 0
Set #Return = 'INSERT DATA FAILED'
ELSE
Set #Return = 'INSERT DATA SUCCESSFULLY'
END
END
I believe I have provided an example for both questions below:
UPDATE T
SET ItemCode = (SELECT PI.ItemCode FROM PartItem AS PI WHERE PI.SO = #SO AND PI.SO_LINE = #SO_LINE),
DESC = CASE #StatusCode WHEN 'N001' THEN 'NEW ORDER'
ELSE CASE #StatusCode WHEN 'PR002' THEN 'PROGRESS' ELSE '' END
END,
<other columns here...>
FROM SAMPLE_TAG_NUMBERTEST AS T

Insert Stored Procedure with null parameters

I want to create an insert stored procedure with null parameters, if pass the value for that parameter then it has to insert or update in database
My stored procedure is:
Create proc [dbo].[SP_InsertOrUpdateCourseDetails]
#CourseID int,
#Tab1Title nvarchar(250) = null,
#Tab1Description nvarchar(max) = null,
#Tab2Title nvarchar(250) = null,
#Tab2Description nvarchar(max) = null,
#Tab3Title nvarchar(250) = null,
#Tab3Description nvarchar(max) = null,
#Tab4Title nvarchar(250) = null,
#Tab4Description nvarchar(max) = null,
#Syllabus nvarchar(max) = null
As
Begin
If NOT EXISTS (Select * from CourseDetail Where CourseID=#CourseID )
Begin
Insert into CourseDetail(CourseID, Tab1Title, Tab1Description,
Tab2Title, Tab2Description,
Tab3Title, Tab3Description, Tab4Title, Tab4Description,
Syllabus)
values (#CourseID, #Tab1Title, #Tab1Description, #Tab2Title, #Tab2Description,
#Tab3Title, #Tab3Description, #Tab4Title, #Tab4Description, #Syllabus)
IF ##ERROR = 0 AND ##ROWCOUNT =1
Begin
Select top 1 CourseID from CourseDetail Order by CourseDetailID Desc
End
Else
Begin
Select 0
End
End
Else
Begin
Update CourseDetail
SET
Tab1Title = #Tab1Title,
Tab1Description = #Tab1Description,
Tab2Title = #Tab2Title,
Tab2Description = #Tab2Description,
Tab3Title = #Tab3Title,
Tab3Description = #Tab3Description,
Tab4Title = #Tab4Title,
Tab4Description = #Tab4Description,
Syllabus = #Syllabus
Where
CourseID = #CourseID
IF ##ERROR = 0 AND ##ROWCOUNT =1
Begin
Select top 1 CourseID from CourseDetail Order by CourseDetailID Desc
End
Else
Begin
Select 0
End
End
End
You can use ISNULL function passing in it SP's parameter as first parameter and default value in case of insert or actual column's value in case of update:
Insert into CourseDetail(CourseID, Tab1Title, Tab1Description,
Tab2Title, Tab2Description,
Tab3Title, Tab3Description, Tab4Title, Tab4Description,
Syllabus)
values (#CourseID, ISNULL(#Tab1Title, 'default value'), ISNULL(#Tab1Description,'default value'), ...
Update CourseDetail
SET
Tab1Title = ISNULL(#Tab1Title, Tab1Title),
Tab1Description = ISNULL(#Tab1Description, Tab1Description),
....
Where
CourseID = #CourseID
But in this case you won't can to set NULL value explicitely even if you'll need

An object or column name is missing or empty

I am getting the following error
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Add a name or single space as the alias name.
for the query show below:
CREATE PROC [dbo].[Sp_Table1] #ctlg_ipt_event_id int
AS
SET NOCOUNT ON
DECLARE #current_status NCHAR(1), #ready_status_code NCHAR(1)
DECLARE #current_action NCHAR(1), #ready_action_code NCHAR(1), #done_action_code NCHAR(1)
DECLARE #pst_user_id int
SELECT #current_status = status_code
,#current_action = action_code
,#pst_user_id = last_mod_user_id
FROM merch_ctlg_ipt_event
WHERE ctlg_ipt_event_id = #ctlg_ipt_event_id
Select #ready_status_code = 'o'
, #ready_action_code = 'a'
, #done_action_code = 'b'
IF #current_status <> #ready_status_code OR #current_action <> #ready_action_code
BEGIN
RETURN
END
BEGIN TRAN
declare #rows int
,#err int
,#i int
,#name nvarchar(50) --COLLATE SQL_AltDiction_Pref_CP850_CI_AS
,#resolved_View_Name_category_id int
,#xref_value int
,#availability_start_date datetime
,#availability_end_date datetime
,#status_code int
,#last_mod_user_id int
,#CT datetime
,#supplier_id int
,#View_Name_id int
select #i = 1
,#CT = current_timestamp
Select Distinct mc.name,
mc.resolved_View_Name_category_id,
mc.xref_value,
mc.availability_start_date,
mc.availability_end_date,
mc.status_code,
CASE WHEN mc.last_mod_user_id = 42
THEN #pst_user_id
ELSE mc.last_mod_user_id
END as last_mod_user_id,
CURRENT_tsp
,IDENTITY(int,1,1) as rn
,si.supplier_id
,si.View_Name_id
into #temp
FROM View_Name AS si
JOIN merch_ctlg_ipt_View_Name AS mc
ON mc.supplier_id = si.supplier_id
AND mc.resolved_View_Name_id = si.View_Name_id
AND mc.cat_imp_event_id = #ctlg_ipt_event_id
AND mc.accept_flag = 'y'
WHERE si.shipper_flag = 'n'
select #rows=##ROWCOUNT,#err=##error
if #rows > 0 and #err=0
Begin
While #i <=#rows
begin
SElect #name = name,
#resolved_View_Name_category_id = resolved_View_Name_category_id,
#xref_value = xref_value,
#availability_start_date = availability_start_date,
#availability_end_date = availability_end_date,
#status_code = mc.status_code,
#last_mod_user_id =last_mod_user_id ,
,#i=#i+1
,#supplier_id=supplier_id
,#View_Name_id=View_Name_id
from #temp
Where rn=#i
UPDATE View_Name
SET name = #name,
View_Name_category_id = #resolved_View_Name_category_id,
xref_value = #xref_value,
availability_start_date = #availability_start_date,
availability_end_date = #availability_end_date,
status_code = #status_code,
last_mod_user_id = #last_mod_user_id ,
last_mod_timestamp = #CT
Where #sup_id = supplier_id
AND #View_Name_id = View_Name_id
AND shipper_flag = 'n'
IF ##ERROR > 0
BEGIN
ROLLBACK TRAN
RETURN
END
End
End
UPDATE
merch_ctlg_ipt_event
SET action_code = #done_action_code,
last_mod_timestamp = #CT
WHERE ctlg_ipt_event_id = #ctlg_ipt_event_id
IF ##ERROR > 0
BEGIN
ROLLBACK TRAN
RETURN
END
COMMIT TRAN
Return
go
Could you please help ?
You have 2 commas in a row here
#last_mod_user_id =last_mod_user_id ,
,#i=#i+1
Also probably not relevant to the error message but you have a line
Where #sup_id = supplier_id
but the declared variable is #supplier_id