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

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);

Related

Generate Next Alphanumeric Code on SQL Server

I need to create a consecutive sequence of varchar(5) (always 5 chars only) code starting from PREVIOUS code.
For example
'00000', '00001', '00002'...'00009', '0000A', '0000B'...'0000Z', '00010','00011'...'ZZZZZ'.
So if I have #PREVIOUS_CODE = '00000', #NEXT_CODE will be '00001'.
If I have #PREVIOUS_CODE = '00009', #NEXT_CODE will be '0000A'
If I have #PREVIOUS_CODE = '0000Z', #NEXT_CODE will be '00010'
So I need something like that
USE [DATABASE]
GO
CREATE PROCEDURE [dbo].[spGetNextCode]
#PREVIOUS_CODE VARCHAR(5)
AS
DECLARE #NEXT_CODE VARCHAR(5)
DO STUFF
...
SELECT #NEXT_CODE AS NEXT_CODE
GO
Any Help?
Just keep an integer counter in the same table and convert it. I'm using the following SQL Server function in one of my applications:
CREATE FUNCTION [dbo].[GetAlphanumericCode]
(
#number BIGINT,
#leadingzeroes INT = 0
)
RETURNS varchar(255)
AS
BEGIN
DECLARE #charPool varchar(36)
SET #charPool = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
DECLARE #result varchar(255)
IF #number < 0
RETURN ''
IF #number = 0
SET #result = '0'
ELSE BEGIN
SET #result = ''
WHILE (#number > 0)
BEGIN
SET #result = substring(#charPool, #number % 36 + 1, 1) + #result
SET #number = #number / 36
END
END
IF #leadingzeroes > 0 AND len(#result) < #leadingzeroes
SET #result = right(replicate('0', #leadingzeroes) + #result, #leadingzeroes)
RETURN #result
END
It should be a trivial task to rewrite it as a stored procedure

How to get stored procedure internal Declare Variable value in SQL Server

This is my stored procedure:
CREATE PROCEDURE MYSP
(#PARAM INT,
#PARAM2 NVARCHAR(34),
#OUTPARAM3 NVARCHAR(34) OUTPUT)
AS
BEGIN
DECLARE #RParam INT
DECLARE #ErrParam2 NVARCHAR(34)
IF(#PARAM = 1 AND #PARAM2 = 'abc' )
BEGIN
SET #OUTPARAM3 = 'EQUAL'
SET #RPARAM = 0
END
ELSE
BEGIN
SET #ERRPARAM2 = 'SOME ERROR..MSG'
SET #RPARAM = -1
END
RETURN #RPARAM
END
And I am trying to get the value of the internally declare variable value.
DECLARE #RParam INT
DECLARE #ErrParam2 NVARCHAR(34)
#RParam is returned but how can I return #ErrParam2 value?
Declare #RP int
Declare #ErrMsg Nvarchar(40)
Exec #RP = MYSP 1,'abc'
You need to specify the output parameter both when the stored procedure is defined and when it is called:
Declare #RP int;
Declare #ErrMsg Nvarchar(40);
Exec #RP = MYSP 1, 'abc' , #ErrMsg output;

Error Pass from nested MSSQL procedure to parent procedure

I have one parent stored procedure and one nested stored procedure. Parent Stored procedure calls the nested stored procedure on loop. Now when there is certain condition matches I have raised the error. When this error is raised I want to stop all the process and return the error.
CREATE Proc [dbo].[Usp_GenSalarySheet](#SalData [HRM].UTDT_SalaryData ReadOnly)
AS
set nocount on
DECLARE #SMT NVARCHAR(MAX)
SET #SMT = 'Create Table ##SalarySheet (StaffID INT,FullName NVARCHAR(1024),PresentDays NVARCHAR(1024),Absent NVARCHAR(1024),Department NVARCHAR(1024),Designation NVARCHAR(1024),'
DECLARE #HopName nvarchar(max)
Declare HOPCursor cursor for select ID from HRM.tbl_HOP
OPEN HOPCursor
FETCH NEXT FROM HOPCursor INTO #HopName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SMT = #SMT + ' [' + #HopName + '] DECIMAL(19,7),'
FETCH NEXT FROM HOPCursor into #HopName
END
SET #SMT = #SMT + '[Total] DECIMAL(19,7))'
CLOSE HOPCursor
DEALLOCATE HOPCursor
print (#smt)
exec (#SMT)
select * into #temp from #SalData
Declare #TopID INT
While (Select Count(*) From #Temp) > 0
Begin
Select Top 1 #TopID = StaffID From #temp
Declare #StaffID INT =(select top 1 StaffID from #temp)
Declare #StaffName NVARCHAR(1024) = (SELECT TOP 1 FullName FROM #temp)
Declare #WorkingDays Int = (SELECT top 1 WorkingDays from #temp)
Declare #Leave INT = (SELECT top 1 [Absent] from #temp)
INSERT INTO ##SalarySheet(StaffID,FullName,[Absent]) values(#StaffID,#StaffName,#Leave)
DECLARE #HOPType INT
DECLARE #Value Decimal(19,7)
DECLARE #CalcVal DECIMAL(19,7) = 0
DECLARE #Formula NVARCHAR(MAX)
DECLARE #Total DECIMAL(19,7)
DECLARE #PayEvery INT
DECLARE #Round Int
Declare HOPList Cursor for SELECT ID,HOPType,Value,Formula,RoundOff,PayEvery FROM HRM.Tbl_HOP order by Schedule
open HOPList
FETCH NEXT FROM HOPList INTO #HopName,#HOPType,#Value,#Formula,#Round,#PayEvery
WHILE ##FETCH_STATUS = 0
BEGIN
if exists(select * from HRM.[Tbl_ContractHOPDetails] where PersonalDetailsID = #StaffID and HOPID = #HopName)
print('select * from HRM.[Tbl_ContractHOPDetails] where PersonalDetailsID = ' + convert(varchar(max), #StaffID) + ' and HOPID =' + convert(varchar(max),#HopName))
begin
if(#HOPType=51)
begin
exec HRM.Usp_GetSalaryValueFromFormula #StaffID,#Formula,#HOPType,#Leave,#WorkingDays,#Value output
set #HOPType= 50
end
if(#HOPType=50)
begin
set #CalcVal = #value
END
IF(#HOPType=38)
BEGIN
SET #CalcVal = #Value - ((#Value/#WorkingDays) * #Leave)
END
if(#PayEvery= 40)
begin
set #CalcVal = ((#CalcVal * #WorkingDays) - (#CalcVal * #Leave))
end
if(#Round = 45)
begin
set #CalcVal = round(#CalcVal,2)
end
else if(#Round = 46)
begin
set #CalcVal = CEILING(#CalcVal)
end
else if(#Round = 47)
begin
set #CalcVal = FLOOR(#CalcVal)
end
set #SMT ='UPDATE ##SalarySheet SET [' + #HopName + '] = ' + cast(#CalcVal as nvarchar(max)) + ' where StaffID = ' + cast(#StaffID as nvarchar(max))
exec (#smt)
end
SET #CalcVal = 0
FETCH NEXT FROM HOPList INTO #HopName,#HOPType,#Value,#Formula,#Round,#PayEvery
END
close HOPList
DEALLOCATE HOPList
set #SMT ='UPDATE ##SalarySheet SET [Total] = ' + cast(#Total as nvarchar(max)) + ' where StaffID = ' + cast(#StaffID as nvarchar(max))
exec (#smt)
Delete #temp Where StaffID = #TopID
end
select * from ##SalarySheet
drop table ##SalarySheet
This is my parent Stored Procudere and nested procedure is as follow:
CREATE proc [HRM].[Usp_GetSalaryValueFromFormula](#StaffID INT,#val nvarchar(max),#HOPType INT,#Leave INT,#WorkingDays INT, #GetResult Decimal(19,7) output)
as
set nocount on
Declare #Formula Varchar(max)
declare #initial INT =0
declare #final INT =0
Declare #DataVal NVARCHAR(MAX) -- set the value from HOP table
declare #FieldVal nvarchar(max)
declare #cnt int = 0
Declare #Complete Int =CHARINDEX ('[',#val,0)
while (#Complete <> 0)
begin
set #initial = CHARINDEX ('[',#val,0)
set #final = CHARINDEX(']',#val,0)
set #FieldVal = SUBSTRING(#val,#initial,(#final-#initial) + 1)
if len(#FieldVal)<>0
begin
select #HOPType = HOPType, #DataVal= ( case when HOPType = 51 then [Formula] else cast([Value] as nvarchar(max)) end) from HRM.Tbl_ContractHOPDetails where PersonalDetailsID = #StaffID and HOPID in(select ID from HRM.tbl_HOP where HOPName = replace(replace(#fieldVal,'[',''),']',''))
if (#DataVal is null or #DataVal ='')
begin
RAISERROR ('Nested HOP is not defined.',11,1)
RETURN
end
print(#DataVal)
if ISNUMERIC(#DataVal)=1
begin
if(#HOPType = 38)
begin
SET #DataVal = cast(#DataVal as decimal(19,7)) - ((cast(#DataVal as decimal(19,7))/#WorkingDays) * #Leave)
end
end
set #val = replace(#val,#fieldVal,#DataVal)
set #fieldVal= ''
set #DataVal = ''
end
set #Complete = CHARINDEX ('[',#val,0)
set #fieldVal =''
set #final =0
set #initial = 0
end
SET #Complete =CHARINDEX ('{',#val,0)
while (#Complete <> 0)
BEGIN
set #initial = CHARINDEX ('{',#val,0)
set #final = CHARINDEX('}',#val,0)
set #FieldVal = SUBSTRING(#val,#initial+1,(#final-#initial)-1)
if len(#FieldVal)<>0
begin
set #DataVal = isnumeric((SELECT 0 FROM [HRM].Tbl_StaffTag where CValue = #FieldVal and StaffID = #StaffID))
set #FieldVal = '{' + #FieldVal + '}'
set #val = replace(#val,#fieldVal,#DataVal)
set #fieldVal= ''
set #DataVal = ''
end
set #Complete = CHARINDEX ('{',#val,0)
set #final =0
set #initial = 0
END
DECLARE #RetrunVal DECIMAL(19,7)
declare #ParmDefinition Nvarchar(512) = '#GetVal decimal(19,7) OUTPUT'
Declare #SMT NVARCHAR(MAX) = ' SET #GetVal = ' + #val
EXECUTE sp_executeSQL #Smt, #ParmDefinition, #GetVal =#RetrunVal OUTPUT
set #GetResult = #RetrunVal
But in current situation it raises error and again from the main procedure it runs next step of loop. But I want to terminate the complete process after this raiserror
Kindly help me
My guess is that RaiseError throws the control back to the caller, which might make the Return statement unreachable. The caller (loop) continues with next iteration.

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

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

Problems with ROLLBACK TRANSACTION inside try/catch

I'm having this error when I try to execute this code:
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.
I know the problem is on the sp [dbo].[QueueInsert], the sp has an error and it goes directly to the catch. It's funny because the first one (EXEC [dbo].[BacthInsert]) is inserting a summary record and after running the sp, I see the record, so is doing a commit and not doing a rollback. What's wrong with this code? thanks!
CREATE PROCEDURE [cnfg].[SendEmail]
(
,#Employees [dbo].[Employees] readonly
,#ApplicationName NVARCHAR(256)
,#ErrorMsg NVARCHAR(300) = NULL OUTPUT
)
AS
BEGIN
DECLARE #ReturnVal INT
DECLARE #ApplicationId UNIQUEIDENTIFIER
DECLARE #NewIdBatch INT
DECLARE #ID INT
DECLARE #EmployeeId INT
DECLARE #Index INT = 1
DECLARE #Total INT
SET NOCOUNT ON;
SET XACT_ABORT ON;
SET #ReturnVal = 0;
SET #ErrorMsg = '';
SET #ApplicationId = [GetId](#ApplicationName);
IF (#ApplicationId IS NULL)
BEGIN
SET #ReturnVal = 1;
SET #ErrorMsg = 'The Application Name does not exist in the database';
Goto ProcedureExit
END
----------------------------------------------------------
BEGIN TRY -- Start Main TRY
----------------------------------------------------------
BEGIN TRANSACTION;
EXEC [dbo].[BacthInsert]
#ParameterId = 1
,#ID = #NewSendEmailBatchId OUTPUT
,#ErrorMsg = #ErrorMsg OUTPUT
IF ( #ErrorMsg <> '' )
BEGIN
SET #ReturnVal = 1;
SET #ErrorMsg = 'There was an error trying to insert data into [dbo].[BacthInsert] table';
RAISERROR(#ErrorMsg, 16, 1)
END
SELECT ROW_NUMBER() OVER ( ORDER BY EmployeeId ) Row,
EmployeeId
INTO #EmpIds
FROM #Employees
SELECT #Total = COUNT(*) FROM #EmpIds
WHILE ( #Index <= #Total )
BEGIN
SELECT #EmployeeId=EmployeeId FROM #EmpIds WHERE Row = #Index
EXEC [dbo].[QueueInsert]
#SendEmailBatchId = #NewIdBatch
,#ID = #ID OUTPUT
,#ErrorMsg = #ErrorMsg OUTPUT
IF ( #ErrorMsg <> '' )
BEGIN
SET #ReturnVal = 1;
SET #ErrorMsg = 'There was an error trying to insert data into [dbo].[QueueInsert] table';
RAISERROR(#ErrorMsg, 16, 1)
END
SET #Index+=1;
END
COMMIT TRANSACTION;
----------------------------------------------------------
END TRY -- End Main TRY
----------------------------------------------------------
----------------------------------------------------------
BEGIN CATCH -- Start Main CATCH
----------------------------------------------------------
SELECT ERROR_MESSAGE()
IF (XACT_STATE()) = -1
BEGIN
ROLLBACK TRANSACTION;
END;
----------------------------------------------------------
END CATCH -- End Main CATCH
----------------------------------------------------------
ProcedureExit:
RETURN #ReturnVal;
END