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

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)

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

Error in running scalar-valued function when different calling method is used

I have this function
CREATE FUNCTION fullName
(
#customer_id int
)
RETURNS varchar(50)
AS
BEGIN
DECLARE #name varchar(50)
SELECT #name = (SELECT name_last + ', ' + name_first FROM DT_CUSTOMERS WHERE customer_id = #customer_id)
RETURN #name
END
When I call/run the function with this code, it works:
SELECT dbo.fullName(356)
But when I use this method, it gives me the error "Invalid object name 'fullName'" with or without the "dbo." before the function name :
SELECT * FROM fullName(356)

SQL Server 2008 R2: Prepare Dynamic WHERE Clause

I have the following stored procedure with four parameters.
Stored procedure spTest:
CREATE PROCEDURE spTest
#Name varchar(20) = '',
#Address varchar(100) = '',
#City varchar(50) = '',
#Pin varchar(50) = ''
AS
DECLARE #DynamicWhere varchar(max)
DECLARE #Query varchar(max)
/* Here I want to prepare a dynamic where clause for all possibilities */
SET #Query = 'SELECT * FROM Test_Table '+ #DynamicWhere +'';
EXECUTE(#Query);
GO
Well I am preparing it like this:
IF #Name = '' AND #Address = '' AND #City = '' AND #Pin = ''
BEGIN
SET #DynamicWhere = '';
END
ELSE IF #Name != '' AND #Address = '' AND #City = '' AND #Pin = ''
BEGIN
SET #DynamicWhere = 'Name ='''+#Name+'''';
END
ELSE IF #Name != '' AND #Address != '' AND #City = '' AND #Pin = ''
BEGIN
SET #DynamicWhere = 'Name ='''+#Name+''' AND Address ='''+#Address+'''';
END
......
......
Many possibilities
Is this a right way OR is there any better way to prepare the dynamic WHERE clause?
It's called catch-all queries and it basically goes like this:
CREATE PROCEDURE spTest
#Name varchar(20) = '',
#Address varchar(100) = '',
#City varchar(50) = '',
#Pin varchar(50) = ''
AS
SELECT *
FROM Test_Table
WHERE (#Name = '' OR Name = #Name)
AND (#Address = '' OR Address = #Address)
AND (#City = '' OR City = #City)
AND (#Pin = '' OR Pin = #Pin);
GO
You also might want to read this article about catch all queries
You can use ISNULL and NULLIF also in this case:
below code should work :
CREATE PROCEDURE spTest
#Name varchar(20) = '',
#Address varchar(100) = '',
#City varchar(50) = '',
#Pin varchar(50) = ''
AS
SET #Name=NULLIF(#Name,'')
SET #Address=NULLIF(#Address,'')
SET #City=NULLIF(#City,'')
SET #Pin=NULLIF(#Pin,'')
SELECT *
FROM Test_Table
WHERE Name = ISNULL(#Name,Name)
AND Address = ISNULL(#Address,Address)
AND City = ISNULL(#City,City)
AND Pin = ISNULL(#Pin,Pin)
GO
I update the #Zohar answer. Define blank is bad habits, ideally define with null and later use blank. So the query will be
CREATE PROCEDURE spTest
#Name varchar(20) = null,
#Address varchar(100) = null,
#City varchar(50) = null,
#Pin varchar(50) = null
AS
SELECT *
FROM Test_Table
WHERE (Name = ISNULL(#Name,'') )
AND (Address = ISNULL(#Address,''))
AND (City = ISNULL(#City,''))
AND (Pin = ISNULL(#Pin,''));
GO
Even I like the #Biswa answer as it use current version of sql server, but Sqlserver 2008R2 does not have this function.

Must declare the scalar variable error for stored procedure

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;

SQL Server: help with a simple stored procedure?

I'm trying to create a simple stored procedure which I can use to write data to a log table. I'm a noob in stored procedures, so what I'm missing here? I get an error saying:
Msg 201, Level 16, State 4, Procedure toLog, Line 0
Procedure or function 'toLog' expects parameter '#messageTime', which was not supplied.
How to modify this code to get this work?
USE <database>
GO
IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'logTable')
DROP TABLE dbo.logTable
GO
CREATE TABLE dbo.logTable (
messageTime DATETIME NULL,
etlJobName NVARCHAR(40) NULL,
whereTo VARCHAR(10) NOT NULL,
messag VARCHAR(255) NULL
)
/*************** procedure ************/
--DROP PROC dbo.toLog
CREATE PROCEDURE dbo.toLog
#messageTime DATETIME,
#etlJobName NVARCHAR(60) = 'unknown',
#whereTo NVARCHAR(20) = 'print',
#messag NVARCHAR(255) = 'empty'
AS
BEGIN
SET #messageTime = GETDATE()
IF #whereTo = 'log' OR #whereTo = 'logandprint'
INSERT INTO logTable(messageTime, etlJobName, whereTo, messag)
VALUES (#messageTime, #etlJobName, #whereTo, #messag)
IF #whereTo = 'print' OR #whereTo = 'logandprint'
PRINT CONVERT(VARCHAR, GETDATE(), 113) + ', ' + #etlJobName + ', ' + #whereTo + ', ' + ', ' + #messag
END
GO
--execution
EXEC dbo.toLog #whereTo = 'log'
It's because your toLog sproc is expecting you to supply the #messageTime parameter, which you haven't done, and it doesn't have a default value like the other parameters.
As you set the #messageTime always to GETDATE() inside the sproc, it looks like you just want to scrap that parameter:
CREATE PROCEDURE dbo.toLog
#etlJobName NVARCHAR(60) = 'unknown',
#whereTo NVARCHAR(20) = 'print',
#messag NVARCHAR(255) = 'empty'
AS
BEGIN
IF #whereTo = 'log' OR #whereTo = 'logandprint'
INSERT INTO logTable(messageTime, etlJobName, whereTo, messag)
VALUES (GETDATE(), #etlJobName, #whereTo, #messag)
IF #whereTo = 'print' OR #whereTo = 'logandprint'
PRINT CONVERT(VARCHAR, GETDATE(), 113) + ', ' + #etlJobName + ', ' + #whereTo + ', ' + ', ' + #messag
END
Or, if you do want to be able to pass in a datetime yourself:
CREATE PROCEDURE dbo.toLog
#messageTime DATETIME = null,
#etlJobName NVARCHAR(60) = 'unknown',
#whereTo NVARCHAR(20) = 'print',
#messag NVARCHAR(255) = 'empty'
AS
BEGIN
IF (#messagetime IS NULL) SET #messagetime = GETDATE()
IF #whereTo = 'log' OR #whereTo = 'logandprint'
INSERT INTO logTable(messageTime, etlJobName, whereTo, messag)
VALUES (#messageTime, #etlJobName, #whereTo, #messag)
IF #whereTo = 'print' OR #whereTo = 'logandprint'
PRINT CONVERT(VARCHAR, #MessageTime, 113) + ', ' + #etlJobName + ', ' + #whereTo + ', ' + ', ' + #messag
END
When You are creating the stored procedure with parameters, At any cause we need to pass the parameter values, when executing stored procedure.
Example 1:
EXEC dbo.toLog '','','',''
In the above line when you are executing the stored procedure , it will not thrown any errors. because passed the Parameters values are a NULL.
Example 2:
EXEC dbo.toLog '','','log',''
In the above line when you are executing the stored procedure , it will not thrown any errors, data will be Logged in your table. Based on the Stored procedure inside script logic