Trying to compose a Stored Procedure at SQL server with programmer logic but not working - sql

Ok here my table - SQL server 2014
Assume that i have the following variables
Computer Hardware > Video Cards
So Computer Hardware is being parent node and Video Cards is being children
Here my stored procedure which is written by programmer logic but not working
Create Procedure insert_Product_Category_With_Parent_Node_Key_pair
(
#cl_CategoryName nvarchar(200),
#cl_ParentCategoryName nvarchar(200),
#cl_InsertedId int Output
)
As
Begin
declare #cl_ParentCategoryId int
declare #cl_Parent_Node_Exists_CategoryId int
set #cl_ParentCategoryId = ISNULL((select cl_CategoryId
from tblProductCategories
where cl_CategoryName=#cl_ParentCategoryName),0)
set #cl_Parent_Node_Exists_CategoryId = ISNULL((select cl_CategoryId
from tblProductCategories
where cl_CategoryName=#cl_CategoryName
and
cl_ParentCategoryId=#cl_ParentCategoryId),0)
CASE
when #cl_Parent_Node_Exists_CategoryId = 0
then
insert into tblProductCategories (cl_CategoryName,cl_ParentCategoryId)
#cl_InsertedId = INSERTED.cl_CategoryId
values (#cl_CategoryName,#cl_ParentCategoryId)
else
#cl_InsertedId = #cl_Parent_Node_Exists_CategoryId
end
end
The error SQL server giving
Msg 156, Level 15, State 1, Procedure insert_Product_Category_With_Parent_Node_Key_pair, Line 17
Incorrect syntax near the keyword 'CASE'.
Msg 102, Level 15, State 1, Procedure insert_Product_Category_With_Parent_Node_Key_pair, Line 22
Incorrect syntax near '#cl_InsertedId'.
Ok here how i want it work
declare #returned_product_categoryId int
exec insert_Product_Category_With_Parent_Node_Key_pair
#cl_CategoryName = 'Video Cards',
#cl_ParentCategoryName = 'Computer Hardware'
#returned_product_categoryId = #cl_InsertedId output
select #returned_product_categoryId
So finally my question how do make this stored procedure work ? My logic is fine however i can't find a way to turn it into SQL logic
When converted to if else logic in that case assignments are giving error

Create Procedure insert_Product_Category_With_Parent_Node_Key_pair
(
#cl_CategoryName nvarchar(200),
#cl_ParentCategoryName nvarchar(200),
#cl_InsertedId int Output
)
AS
BEGIN
SET NOCOUNT ON;
declare #cl_ParentCategoryId int;
declare #cl_Parent_Node_Exists_CategoryId int;
set #cl_ParentCategoryId = ISNULL((select cl_CategoryId
from tblProductCategories
where cl_CategoryName = #cl_ParentCategoryName),0)
set #cl_Parent_Node_Exists_CategoryId = ISNULL((select cl_CategoryId
from tblProductCategories
where cl_CategoryName = #cl_CategoryName
and
cl_ParentCategoryId = #cl_ParentCategoryId),0)
IF (#cl_Parent_Node_Exists_CategoryId = 0)
BEGIN
insert into tblProductCategories (cl_CategoryName,cl_ParentCategoryId)
values (#cl_CategoryName,#cl_ParentCategoryId)
SET #cl_InsertedId = SCOPE_IDENTITY();
END
ELSE
BEGIN
SET #cl_InsertedId = #cl_Parent_Node_Exists_CategoryId;
END
END

You missed set before cl_InsertedId - or u also use Scope_Identity()
Create Procedure insert_Product_Category_With_Parent_Node_Key_pair
(
#cl_CategoryName nvarchar(200),
#cl_ParentCategoryName nvarchar(200),
#cl_InsertedId int Output
)
As
Begin
declare #cl_ParentCategoryId int
declare #cl_Parent_Node_Exists_CategoryId int
set #cl_ParentCategoryId = ISNULL((select cl_CategoryId
from tblProductCategories
where cl_CategoryName=#cl_ParentCategoryName),0)
set #cl_Parent_Node_Exists_CategoryId = ISNULL((select cl_CategoryId
from tblProductCategories
where cl_CategoryName=#cl_CategoryName
and
cl_ParentCategoryId=#cl_ParentCategoryId),0)
if #cl_Parent_Node_Exists_CategoryId = 0
begin
insert into tblProductCategories (cl_CategoryName,cl_ParentCategoryId)
set #cl_InsertedId = INSERTED.cl_CategoryId
values (#cl_CategoryName,#cl_ParentCategoryId)
end
else
begin
set #cl_InsertedId = #cl_Parent_Node_Exists_CategoryId
end
end

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 varaibles if statement

I have a issue resulting in the following error.
declare #transDate datetime = GETDATE();
declare #main_work_center as varchar(50) = 'PMOM';
declare #team as varchar(1) = '';
declare #full_work_center as varchar(50);
IF(#team = '' OR #team IS NULL) then
#full_work_center = #main_work_center;
else
#full_work_center = #main_work_center + #team;
end if
THis is the error: Msg 156, Level 15, State 1, Line 5 Incorrect syntax near the keyword 'then'.
You have multiple syntax errors in your code, that's just the first.
then is not allowed with an if
You need a set before your variable assignments in the if/else
There is no if after the end
I like to wrap the code inside the two blocks of an if/else with begin and end, much like the curly braces in other languages, for clarity.
Fully corrected code:
declare #transDate datetime = GETDATE();
declare #main_work_center as varchar(50) = 'PMOM';
declare #team as varchar(1) = '';
declare #full_work_center as varchar(50);
IF(#team = '' OR #team IS NULL)
begin
set #full_work_center = #main_work_center;
end
else
begin
set #full_work_center = #main_work_center + #team;
end;

I'm getting an error "Msg 8114, Level 16, State 5, Procedure sp_DRPL_MassChangeClient, Line 0 Error converting data type varchar to int."

I've checked all the tables in question and I've declared all variables correctly.
the code below calls on a very basic stored procedure which can be provided if needed (I'm not sure how to add it in here properly)
DECLARE #DebtorsDebtID AS uniqueidentifier
DECLARE #OldClient AS varchar(15)
DECLARE #ClientID AS varchar(15)
DECLARE #UserName AS varchar(20)
DECLARE #Rows AS int
DECLARE #Count AS int
DECLARE #ID AS int
DECLARE #DebtID AS int
SET #UserName = 'rhys.bartley'
SET #OldClient = 'TMTEST'
SET #ClientID = 'ECCOMMERCIAL'
SELECT tblDebt.PK_DebtID INTO #tmp
FROM tblDebt
WHERE tblDebt.PK_DebtID = 233101
SELECT #Rows = ##ROWCOUNT, #Count = 0
WHILE (#Count < #Rows)
BEGIN
SELECT TOP 1 #ID = PK_DebtID FROM #tmp
SELECT #DebtorsDebtID = PK_DebtorsDebtID FROM tblDebtorsDebt where FK_DebtID = #ID
EXEC sp_DRPL_MassChangeClient #DebtorsDebtID,#OldClient,#ClientID,#UserName,#DebtID
DELETE #tmp WHERE PK_DebtID = #ID
SELECT #Count = #Count + 1
END
sp_DRPL_MassChangeClient
USE [BailiffDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_DRPL_MassChangeClient]
#DebtorsDebtID AS uniqueidentifier,
#DebtID AS int,
#OldClient AS varchar(15),
#ClientID AS varchar(15),
#UserName AS varchar(20)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #BatchNo int
SET #BatchNo = 2457
UPDATE tblArrangement SET FK_ClientID = #ClientID WHERE FK_DebtorsDebtID = #DebtorsDebtID
UPDATE tblDebt SET FK_ClientID = #ClientID WHERE PK_DebtID = #DebtID
UPDATE tblDebtorsDebt SET FK_ClientID = #ClientID WHERE PK_DebtorsDebtID = #DebtorsDebtID
UPDATE tblLetterActivity SET FK_ClientID = #ClientID WHERE FK_DebtID = #DebtID
UPDATE tblTransactions SET FK_ClientID = #ClientID WHERE FK_DebtID = #DebtID
UPDATE tblTransactionsDistributed SET FK_ClientID = #ClientID WHERE FK_DebtID = #DebtID
UPDATE tblTransactionsDistributed_Cancelled SET FK_ClientID = #ClientID WHERE FK_DebtID = #DebtID
UPDATE tblTransactions_Cancelled SET FK_ClientID = #ClientID WHERE FK_DebtID = #DebtID
UPDATE tblDebtLoad SET FK_ClientID = #ClientID WHERE PK_DebtID = #DebtID
UPDATE tblBatchNo SET FK_ClientID = #ClientID WHERE PK_BatchNo = #BatchNo
END
This is what your passing
EXEC sp_DRPL_MassChangeClient #DebtorsDebtID,#OldClient,#ClientID,#UserName,#DebtID
the second #variable is #OldClient which is declared as varchar into
#DebtorsDebtID AS uniqueidentifier,
#DebtID AS int,
The second variable is #DebtID declared as INT hence the error thrown

sql server The multi-part identifier " " could not be bound stored procedure

I create a stored procedure in which I call two functions .
I'm getting an error:
Msg 4104, Level 16, State 1, Procedure Add_Translation, Line 25
The multi-part identifier ".word" could not be bound.
This is my stored procedure:
ALTER PROCEDURE [dbo].[Add_Translation]
#english nvarchar(70),
#kurdish nvarchar(70),
#english_category int,
#kurdish_category int,
#result int out
AS
BEGIN
SET NOCOUNT ON;
if #english is not null and #kurdish is not null and #english_category is not null and #kurdish_category is not null
begin
declare #intEnId int=-1;
exec #intEnId = Check_English_word #text = #english;
declare #identityEnglish int;
declare #identityKurdish int;
if #intEnId = -1
begin
insert into english_table values(#english, #english_category);
set #identityEnglish = SCOPE_IDENTITY();
end
else
begin
set #identityEnglish = (select e.english_id from english_table e where UPPER(.word)=UPPER(#english));
end
declare #intKuId int=-1;
exec #intKuId=Check_Kurdish_Word #word=#kurdish;
if #intKuId =-1
begin
insert into kurdish_table values(#kurdish, #kurdish_category);
set #identityKurdish = SCOPE_IDENTITY();
end
else
begin
set #identityKurdish = (select k.kurdish_id from kurdish_table k where upper(k.word)=upper(#kurdish));
end
declare #translated int =0;
exec #translated = Check_Translation #english_id = #identityEnglish, #kurdish_id = #identityKurdish;
if #translated=0
begin
insert into transactions values(#identityEnglish, #identityKurdish);
set #result = 1;
end
else
begin
set #result = 2;
end
end
else
begin
set #result = 0;
end
END
Here is the first function:
ALTER FUNCTION [dbo].[Check_English_word]
(
#text nvarchar(70)
)
RETURNS int
AS
BEGIN
DECLARE #Result int
set #Result=-1;
if #text is not null
begin
SELECT #Result = e.english_id
from english_table e
where UPPER(e.word) = UPPER(#text);
end
RETURN #Result
END
Second function:
ALTER FUNCTION [dbo].[Check_Kurdish_Word]
(
#word nvarchar(70)
)
RETURNS int
AS
BEGIN
DECLARE #Result int
set #Result=-1;
if #word is not null
begin
SELECT #Result = k.kurdish_id
from kurdish_table k
where UPPER(k.word) = UPPER(#word);
end
RETURN #Result
END
You are missing an e in this line
set #identityEnglish=(select e.english_id from english_table e
where UPPER(.word)=UPPER(#english));
Change it to
set #identityEnglish=(select e.english_id from english_table e
where UPPER(e.word)=UPPER(#english));
Also, it is good practice to specify columns when doing an insert -
ie
insert into english_table values(#english,#englsih_category);
should be
insert into english_table (word, category) values(#english,#englsih_category);

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