Must declare the scalar variable error for stored procedure - sql

I have following stored procedure:
CREATE procedure validateLogin
(
#password varchar(200),
#username varchar(100),
#IpAddress varchar(100)
)
AS
BEGIN
Declare #qry varchar(max), #LockedIp varchar(max), #LockedTime DateTime, #TimeDifference int;
set #qry = 'select IdUser, UserName, FirstName, LastName, idOrg, Users.idRole, Roles.Title as [Role], Allowed_IP from Users, Roles where Users.idRole = Roles.idRole
and lower(UserName) = #username and [password] = #password' ;
select
#LockedIp = isnull(Allowed_IP,''),
#LockedTime = isnull(LockedTime, getDate())
from Users
where UserName = ISNULL(#username,'');
SELECT
#TimeDifference = DATEDIFF(MINUTE, #LockedTime, GETDATE())
IF exists(select * from Users where UserName = #username AND Password = #password AND Active = 1)
BEGIN
IF exists(select * from Users where UserName = #username AND isnull(IsLocked, 0) = 1)
BEGIN -- BE1
IF(#LockedIp = #IpAddress)
BEGIN --BE2
IF (#TimeDifference >5)
BEGIN --BE5
UPDATE Users
SET IsLocked = 0, LockedTime = null
WHERE UserName = ISNULL(#username,'')
exec(#qry);
END --BE5
ELSE
BEGIN
select 'Your Account has been Locked.Try after some time' as Error
END
END --BE2
Else IF(#LockedIp!=#IpAddress)
BEGIN --BE4
UPDATE Users
SET IsLocked = 0, LockedTime = null
WHERE UserName = isnull(#username,'')
exec(#qry);
END --BE4
END -- BE1
Else
BEGIN --BE3
exec(#qry);
END -- BE3
END
END
Go
When I execute this through:
exec validateLogin '|161|217|4|51','admin','127.0.0.1'
I get following error:
Msg 137, Level 15, State 2, Line 3
Must declare the scalar variable "#username".
I have declared this variable in my parameter list, then also error is showing up.
Please help me.
How can I resolve this?

EXEC() will execute in a different scope, so your parameters are not found. You should use sp_executesql and add your parameters that way:
DECLARE #qry NVARCHAR(MAX);
SET #qry = N'select IdUser,UserName,FirstName,LastName,idOrg,Users.idRole,Roles.Title as [Role],Allowed_IP
from Users,Roles
where Users.idRole=Roles.idRole
and lower(UserName)=#username
and [password]=#password' ;
EXECUTE sp_executesql #qry,
N'#username varchar(100), #password varchar(200)',
#Username,
#Password;

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

How to execute a string in SQL Server and stored its result into a variable

ALTER PROCEDURE [dbo].[GetEmployeeSal]
#Mode varchar(50) = '',
#IsMultiple bit = 0,
#EmployeeMstID bigint = 0,
#EmployeeMstIDs varchar(MAX) = '',
#Message varchar(100) = ''
AS
BEGIN
BEGIN TRANSACTION
BEGIN TRY
IF (#Mode = 'GetEmployeeSal')
BEGIN
IF(#IsMultiple = 0)
BEGIN
SELECT #CurrentSal = COUNT(1)
FROM EmployeeMst
WHERE EmployeeMstID = #EmployeeMstID AND IsFinancialYear = 1
SELECT #PreviousSal = COUNT(1)
FROM EmployeeMst
WHERE EmployeeMstID = #EmployeeMstID
IF (#CurrentSal = #PreviousSal)
BEGIN
SET #Message = 'No Salary Revision has been performed'
END
END
ELSE
BEGIN
EXEC ('SELECT #CurrentSal = COUNT(1)
FROM EmployeeMst
WHERE EmployeeMstID IN (' + #EmployeeMstIDs + ')
AND IsFinancialYear = 1')
EXEC ('SELECT #PreviousSal = COUNT(1)
FROM EmployeeMst
WHERE EmployeeMstID IN '( + #EmployeeMstIDs + )'')
IF(#CurrentSal = #PreviousSal)
BEGIN
SET #Message = 'No Salary Revision has been performed'
END
END
END
IF(##ERROR = 0)
BEGIN
COMMIT TRANSACTION
END
ELSE
ROLLBACK TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
END CATCH
END
Your problem is: #CurrentSal variable is not in the context of your EXEC statement.
How to execute a string in SQL Server and stored its result into a
variable
You can use sp_executequery and output like this
DECLARE #CurrentSal INT
DECLARE #sql nvarchar(max) = 'select #CurrentSal = 2'
--EXEC #sql
EXEC sp_executesql #sql, N'#CurrentSal nvarchar(20) OUTPUT', #CurrentSal OUTPUT
SELECT #CurrentSal
Demo link: http://rextester.com/IHBP16111

Stored procedure for Login Application

I have a table with the user details like
id
fname
lname
role
branch
email
password
I have a stored procedure for the login validation which takes the values of email and password, validates and send out the success message.
The validation is working now. I need to fetch the values of fname, lname, role and branch too.
Here is the code:
USE [Project]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[usp_loginuser]
(#Email varchar(100),
#password varchar(100)
)
AS
BEGIN
DECLARE #msg nvarchar(2048)
SET NOCOUNT ON
--select * from dbo.userdetails where email=#userEmail and pwd=#password
BEGIN TRY
Declare #flag bit
SET #flag = 0
IF EXISTS(Select * from userdetails
where ltrim(rtrim(email)) = ltrim(rtrim(#Email)) AND ltrim(rtrim(pwd)) = ltrim(rtrim(#password))
AND isactive = 1)
BEGIN
SET #flag =1;
END
ELSE
BEGIN
SET #flag =0;
END
SELECT #flag [IsSuccess]
END TRY
BEGIN CATCH
SET #msg = error_message()
RAISERROR (#msg, 16, 1)
END CATCH
SET NOCOUNT OFF
END
Here is the code
ALTER Procedure [dbo].[usp_loginuser]
(#Email varchar(100),
#password varchar(100),
#fname varchar(100) output,
#lname varchar(100) output
)
AS
BEGIN
DECLARE #msg nvarchar(2048)
SET NOCOUNT ON
BEGIN TRY
Declare #flag bit
SET #flag = 0
IF EXISTS(Select #fname = fname, #lname = lname from userdetails
where ltrim(rtrim(email)) = ltrim(rtrim(#Email)) AND ltrim(rtrim(pwd)) = ltrim(rtrim(#password))
AND isactive = 1)
BEGIN
SET #flag =1;
END
ELSE
BEGIN
SET #flag =0;
END
SELECT #flag [IsSuccess], #fname, #lname
END TRY
BEGIN CATCH
SET #msg = error_message()
RAISERROR (#msg, 16, 1)
END CATCH
SET NOCOUNT OFF
END
BEGIN TRY
Declare #flag bit
SET #flag = 0
IF EXISTS(Select * from userdetails
where ltrim(rtrim(email)) = ltrim(rtrim(#Email)) AND ltrim(rtrim(pwd)) = ltrim(rtrim(#password))
AND isactive = 1)
BEGIN
SET #flag =1;
END
ELSE
BEGIN
SET #flag =0;
END
SELECT fname, lname, role, branch from userdetails
where ltrim(rtrim(email)) = ltrim(rtrim(#Email)) AND ltrim(rtrim(pwd)) = ltrim(rtrim(#password))
END TRY
If you get an empty data set, its a failure else success

How to select the ALL passed parameter values inside the stored procedure in SQL like SQL Trace

How to select all parameters and values passed to the stored procedure as like in SQL Trace, inside the procedure using any ## function without any customization.
For Example I have a stored procedure like
CREATE PROC test_Procedure
#ln varchar(25) = '',
#fn varchar(25) = '',
#dob datetime = NULL,
#id INT = 0
AS
BEGIN
SELECT * FROM tb_users
WHERE ln= #ln
AND fn = #fn
AND dob = #dob
AND Id = #id
------------ SELECT ##
END
If I called the procedure like
EXEC [dbo].test_Procedure #ln = N'a',#fn = NULL,#dob = NULL,#id = 1
I need to select this exact string inside the procedure using any built in function or user defined function .
If you're trying to output debugging style info you could use something like this;
SELECT CONCAT('test_Procedure #ln = ', #ln, ', #fn = ', #fn, ', #dob = ', #dob, ', #id = ', #id)

Dont want Select variable displaying values

It might be simple but I been having trouble figuring out.
I have a piece of code(Similar to Below Code) where I am assigning bunch of values to bunch of variables via select, it does the job but when I am running it I am getting result set which is causing my SSMS to crash is there way to avoid this....
DECLARE #Name VARCHAR(100)
DECLARE #LastName VARCHAR(100)
DECLARE #Address VARCHAR(100)
SELECT TOP 1
#Name = Name
#LastName = LastName
#Address = Address
From Person.Address
Where Name = 'Name'
Order By ID
I am using the above code in a loop where I am processing around 3-400K rows and pass this variables to a stored procedure, each top 1 select statement throws a result set causing my SSMS to crash I dont really need the select top 1 values to be displayed, any idea how to get rid of this?....
Any help would be much appreciated.
---As requested below is the code, I have hashed few things but this is what it is and I am running it from Query Analayzer as this is only 1 time process so we dont need SP to be created.
DECLARE #retstat INT
DECLARE #Name VARCHAR(255)
DECLARE #Lang TINYINT
DECLARE #Address CHAR(10)
DECLARE #ID INT
DECLARE #BranchSeqNo INT
DECLARE #AddressCode VARCHAR(10)
DECLARE #Address1 VARCHAR(50)
DECLARE #City VARCHAR(30)
DECLARE #State VARCHAR(3)
DECLARE #PostalCode VARCHAR(15)
DECLARE #Country VARCHAR(30)
SET #ID = NULL
UPDATE RAWClaimTable Set Processed = 0 where Processed is null
UPDATE RAWClaimTable SET ErrorCode = NULL ,ErrorMessage = NULL ,Processed = 0
WHERE ErrorMessage IS NOT NULL AND CLAIMID is null
WHILE EXISTS ( SELECT *
FROM RAWClaimTable
WHERE Processed = 0 )
BEGIN
-----Initialize Default Variables
SET #Lang = 0
SET #Address = 'Import'
SET #SaveMode = 0
SET #ID = Null
SELECT TOP 1
#LossDate = LossDate ,
#ClaimDate = ClaimDate ,
#OpenDate = OpenDate ,
#Receivedate = ReceiVeDate ,
#Name = Name ,
#Address = Address ,
#Address1 = Address1 ,
#City = City ,
#State = State ,
#PostalCode = PostalCode ,
#Country = Country
FROM RAWClaimTable
WHERE Processed = 0
ORDER BY ClaimID
BEGIN TRY
EXEC #RetStat = Usp_ProcessRawData #Lang, #Address, #SaveMode, #ID OUT,
#BranchSeqNo, #OriginalBranchSeqNo, #IncidentID,
#AssignmentTypeCode, #PartnershipID, #AccountID,
END TRY
BEGIN CATCH
SELECT #RetStat = ##Error
if ##Trancount > 0 rollback tran
IF #RetStat != 0
BEGIN
update RAWClaimTable set Errormessage = ERROR_MESSAGE() where ClaiMKey = #Name
END
END CATCH
IF #ID IS NOT NULL
BEGIN
UPDATE RAWClaimTable
SET ClaimID = #ID ,
Processed = 1
WHERE ClaiMKey = #Name
END
ELSE
BEGIN
UPDATE RAWClaimTable
SET Processed = 1
WHERE ClaiMKey = #Name
END
END
Use a CURSOR to loop thru your rows!
SET #Lang = 0
SET #Address = 'Import'
SET #SaveMode = 0
SET #ID = Null
DECLARE my_cursor CURSOR FOR
SELECT LossDate, ClaimDate, OpenDate, ReceiVeDate, Name, Address,
Address1, City, State, PostalCode, Country
FROM RAWClaimTable
WHERE Processed = 0
OPEN my_cursor
FETCH NEXT FROM my_cursor
INTO #LossDate, #ClaimDate, #OpenDate, #Receivedate, #Name, #Address,
#Address1, #City, #State, #PostalCode, #Country
WHILE ##FETCH_STATUS = 0
BEGIN
BEGIN TRY
EXEC #RetStat = Usp_ProcessRawData #Lang, #Address, #SaveMode, #ID OUT,
#BranchSeqNo, #OriginalBranchSeqNo, #IncidentID,
#AssignmentTypeCode, #PartnershipID, #AccountID,
END TRY
BEGIN CATCH
SELECT #RetStat = ##Error
if ##Trancount > 0 rollback tran
IF #RetStat != 0
BEGIN
update RAWClaimTable set Errormessage = ERROR_MESSAGE()
where ClaiMKey = #Name
END
END CATCH
IF #ID IS NOT NULL
BEGIN
UPDATE RAWClaimTable
SET ClaimID = #ID ,
Processed = 1
WHERE ClaiMKey = #Name
END
ELSE
BEGIN
UPDATE RAWClaimTable
SET Processed = 1
WHERE ClaiMKey = #Name
END
FETCH NEXT FROM my_cursor
INTO #LossDate, #ClaimDate, #OpenDate, #Receivedate, #Name, #Address,
#Address1, #City, #State, #PostalCode, #Country
END