Executing Stored Procedure - sql-server

I cant execute my SP ( Example when i type spGetNamebyID 1)
Here is my code
alter proc spGetNameByID
#ID int,
#Name varchar(50) output,
#Gender varchar (50) output
as
begin
Select #Name = Name, #Gender = Gender from tblEmployee where ID = #ID
end
Declare #Name varchar(50), #Gender varchar(50)
Execute spGetNameByID 2, #Name out, #Gender out
Print 'Name is ' + #Name + ' Gender ' + #Gender
I get this error message
Msg 201, Level 16, State 4, Procedure spGetNameByID, Line 0 Procedure
or function 'spGetNameByID' expects parameter '#Name', which was not
supplied.

Try this
Declare #Name varchar(50), #Gender varchar(50)
exec spGetNameByID #ID = 2, #Name = #Name output, #Gender = #Gender output
You can also right click on the Stored Procedure in Sql Management Studio, execute the procedure and it will show you the query.

I think I got it. You must include Declare and print
Declare #Name1 varchar(50), #Gender1 varchar(50)
Execute spGetNameByID 2, #Name1 out, #Gender1 out
Print 'Name is ' + #Name1 + ' Gender ' + #Gender1

Try writing your execute line like this
Execute spGetNameByID #ID = 2
and leave out
, #Name = #Name output, #Gender = #Gender output

Related

Assign result of dynamic SQL in Procedure A to variable defined in Procedure B

I am struggling with getting the result back for a dynamic query that is being called from a different stored procedures. Here is what I am trying to achieve.
Procedure A:
CREATE PROCEDURE A
#C1 int, #F1 int
AS
SET #SQL = 'SELECT ID FROM EMPLOYEE_TABLE WHERE '+#C1+' = +'#F1'
EXEC(#SQL)
Procedure B:
CREATE PROCEDURE B
#C1 int, #F1 int
AS
DECLARE #Result INT
EXEC #Result = A #C1, #F1
I need to run stored procedure B and let it return back to me the result. I just cannot seem to get the correct result back. How can I fix this problem?
You can try the following two store procedures query statement
Procedure A:
ALTER PROCEDURE A
#C1 VARCHAR(250),
#F1 int
AS
DECLARE #SQL AS VARCHAR(MAX);
SET #SQL = 'SELECT ID FROM PatientTest WHERE '+ #C1+' = ' + CONVERT(VARCHAR(12),#F1)
EXEC(#SQL)
Procedure B:
ALTER PROCEDURE B
#C1 VARCHAR(250),
#F1 int
AS
Declare #Result int
EXEC #Result = A #C1, #F1
If you will face further problem, please let me know in comment. Thanks.
Try these two. I think you will meet your expected result.
Procedure 1
CREATE PROCEDURE GetValue
#ColumnName VARCHAR(250),
#ColumnValue VARCHAR(250)
AS
DECLARE #SQL AS VARCHAR(MAX);
SET #SQL = 'SELECT Email FROM Person WHERE '+ #ColumnName + ' = ''' + #ColumnValue + ''''
EXEC (#SQL)
-- EXEC GetValue 'MobileNo', '+8801919111333'
Procedure 2
CREATE PROCEDURE ReturnValue
#ColumnName VARCHAR(250),
#ColumnValue VARCHAR(250)
AS
DECLARE #Result VARCHAR(250)
EXEC #Result = GetValue #ColumnName, #ColumnValue
-- EXEC ReturnValue 'MobileNo', '+8801919111333'

Stored procedure with table name and values as parameters

I have problems for insert values with a stored procedure with values as parameters and table name too. this is part of my table:
My table:
CREATE TABLE [dbo].[INGRESOLOTEMP_100]
(
[CLIENTE_CODIGO] [SMALLINT] NOT NULL,
[CAJA_CODIGO] [nvarchar](20) NULL,
[CAJA_NUMERO] [SMALLINT] NOT NULL,
)
My stored procedure:
CREATE PROCEDURE [dbo].[SP_LOT_INSERTLOTEMP]
#IDENT_TABLA NVARCHAR(10),
#CLIENTE_CODIGO SMALLINT,
#CAJA_CODIGO NVARCHAR(15),
#CAJA_NUMERO SMALLINT
AS
DECLARE #NOMBRE_TABLA NVARCHAR(40)
SELECT
#NOMBRE_TABLA = 'INGRESOLOTEMP_' + CONVERT(VARCHAR(100), #IDENT_TABLA)
SELECT
#CAJA_CODIGO = CONVERT(VARCHAR(20), #CAJA_CODIGO)
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = 'INSERT into dbo.' + quotename(#NOMBRE_TABLA) +
' (CLIENTE_CODIGO, CAJA_CODIGO, CAJA_NUMERO) VALUES (' +
CONVERT(VARCHAR(20),#CLIENTE_CODIGO) + ',' + #CAJA_CODIGO + ',' +
CONVERT(VARCHAR(20),#CAJA_NUMERO) +
')'
EXEC sp_executesql #SQL
My table name is formed by a table name + an Id (every user has one)
But the problem is when I execute the stored procedure:
SP_LOT_INSERTLOTEMP 100, 123, 'uio123', 1
I have an error in SQL with value: 'uio123'
But if I execute:
SP_LOT_INSERTLOTEMP 100, 123, 80, 1
The insert is perfect, The problem is that I need insert numeric and text values, even date time values too. I realized varchar conversions in the stored procedure, but I don't get it yet.
Anyone, have an Idea?
Please I hope you can help me.
Gregg, Giorgi...
Thanks, I followed your advices, I think I get it:
ALTER PROCEDURE [dbo].[SP_LOT_INSERTLOTEMP]
#IDENT_TABLA NVARCHAR(10),
#CLIENTE_CODIGO SMALLINT,
#CAJA_CODIGO NVARCHAR(15),
#CAJA_NUMERO SMALLINT
AS
BEGIN
DECLARE #NOMBRE_TABLA NVARCHAR(40)
SELECT #NOMBRE_TABLA = 'INGRESOLOTEMP_' + CONVERT(VARCHAR(100),#IDENT_TABLA)
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = 'INSERT into dbo.' + #NOMBRE_TABLA
SET #SQL += '(CLIENTE_CODIGO, CAJA_CODIGO, CAJA_NUMERO) VALUES ('
SET #SQL += CONVERT(VARCHAR(20), #CLIENTE_CODIGO) + ', '
SET #SQL += '''' + CONVERT(VARCHAR(20), #CAJA_CODIGO) + ''', '
SET #SQL += CONVERT(VARCHAR(20), #CAJA_NUMERO) + ')'
DECLARE #ParmDefinition nvarchar(500)
SET #ParmDefinition = '#IDENT_TABLA NVARCHAR(10), #CLIENTE_CODIGO SMALLINT, #CAJA_CODIGO NVARCHAR(15), #CAJA_NUMERO SMALLINT'
SELECT #sql
PRINT #sql
EXEC sp_executesql #SQL, #ParmDefinition, #IDENT_TABLA, #CLIENTE_CODIGO, #CAJA_CODIGO, #CAJA_NUMERO
END
And when I print what execution contains:
EXEC [SP_LOT_INSERTLOTEMP] 100, 123, 'UIO123', 6
I have this:
INSERT into dbo.INGRESOLOTEMP_100(CLIENTE_CODIGO, CAJA_CODIGO, CAJA_NUMERO) VALUES (123, 'UIO123', 6)
I will continue, If I have any question, I hope somebody or you, can help me.
Thanks.
The problem is in varchar column. Notice the generated statements for
EXEC SP_LOT_INSERTLOTEMP 100, 123, 'uio123', 1
EXEC SP_LOT_INSERTLOTEMP 100, 123, 80, 1
INSERT into dbo.[INGRESOLOTEMP_100] (CLIENTE_CODIGO, CAJA_CODIGO, CAJA_NUMERO) VALUES (123,uio123,1)
INSERT into dbo.[INGRESOLOTEMP_100] (CLIENTE_CODIGO, CAJA_CODIGO, CAJA_NUMERO) VALUES (123,80,1)
Try uncommenting --PRINT #SQL and see yourself the resulting statements.
You should provide additional quotes. Try this:
ALTER PROCEDURE [dbo].[SP_LOT_INSERTLOTEMP]
#IDENT_TABLA NVARCHAR(10),
#CLIENTE_CODIGO SMALLINT,
#CAJA_CODIGO NVARCHAR(15),
#CAJA_NUMERO SMALLINT
AS
DECLARE #NOMBRE_TABLA NVARCHAR(40)
SELECT #NOMBRE_TABLA = 'INGRESOLOTEMP_' + CONVERT(VARCHAR(100),#IDENT_TABLA)
SELECT #CAJA_CODIGO = CONVERT(VARCHAR(20), #CAJA_CODIGO)
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = 'INSERT into dbo.' + quotename(#NOMBRE_TABLA) +
' (CLIENTE_CODIGO, CAJA_CODIGO, CAJA_NUMERO) VALUES (' +
+ CONVERT(VARCHAR(20),#CLIENTE_CODIGO) +','''/*changes here*/ + #CAJA_CODIGO + ''','/*changes here*/ +
CONVERT(VARCHAR(20),#CAJA_NUMERO) +
')'
--PRINT #SQL
EXEC sp_executesql #SQL
Several changes needed to be made to your procedure; see below:
ALTER PROCEDURE [dbo].[SP_LOT_INSERTLOTEMP]
#IDENT_TABLA NVARCHAR(10),
#CLIENTE_CODIGO SMALLINT,
#CAJA_CODIGO NVARCHAR(15),
#CAJA_NUMERO SMALLINT
AS
BEGIN
DECLARE #NOMBRE_TABLA NVARCHAR(40)
SELECT #NOMBRE_TABLA = 'INGRESOLOTEMP_' + CONVERT(VARCHAR(100),#IDENT_TABLA)
SELECT #CAJA_CODIGO = CONVERT(VARCHAR(20), #CAJA_CODIGO)
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = 'INSERT into dbo.' + #NOMBRE_TABLA
SET #SQL += '(CLIENTE_CODIGO, CAJA_CODIGO, CAJA_NUMERO)
VALUES (#CLIENTE_CODIGO, #CAJA_CODIGO, #CAJA_NUMERO)'
DECLARE #ParmDefinition nvarchar(500)
SET #ParmDefinition = '#IDENT_TABLA NVARCHAR(10), #CLIENTE_CODIGO SMALLINT, #CAJA_CODIGO NVARCHAR(15), #CAJA_NUMERO SMALLINT'
SELECT #sql
EXEC sp_executesql #SQL, #ParmDefinition, #IDENT_TABLA, #CLIENTE_CODIGO, #CAJA_CODIGO, #CAJA_NUMERO
END

Table Name Variable in select statement in sql server

I want to use tablename variable in select statement, but it is giving error
- Must declare the table variable "#table"
alter PROCEDURE testTblName
(
#id int,
#name varchar(50)
)
AS
BEGIN
declare #table varchar(50)
declare #add varchar(150)
set #table = 'DBTest..testMaster'
select #add = address from #table where id=#id and name=#name
END
This is a snap shot of my code
You need to use dynamic sql for this:
alter PROCEDURE testTblName
(
#id int,
#name varchar(50)
)
AS
BEGIN
declare #table varchar(50)
declare #add varchar(150)
set #table = 'DBTest..testMaster'
DECLARE #sql NVARCHAR(MAX)
SELECT #sql = 'select #add = address from ' + #table + ' where id= ' + #id + ' and name= ' + #name
EXEC sp_executesql #sql
END
You can't use a variable for your table name. When you do select address from #table SQL expects #table to be a variable of the table type, not a scalar.
You're looking to do something like this:
ALTER PROCEDURE testTblName
(
#id INT,
#name VARCHAR(50)
)
AS
BEGIN
DECLARE #table VARCHAR(50),
#add VARCHAR(150),
#params VARCHAR(200),
#sql VARCHAR(200);
SET #params = '#add VARCHAR(50) OUTPUT';
SET #table = 'DBTest..testMaster'
SET #sql = 'SELECT #add = address FROM ' + #table + ' WHERE id=' + #id + ' AND name=' + #name
EXEC sp_executesql #sql, #params, #add OUTPUT;
...
...
END
I think, u will have to give something like this.
alter PROCEDURE testTblName
(
#id int,
#name varchar(50)
)
AS
BEGIN
declare #table varchar(50)
declare #add varchar(Max)
set #table = 'DBTest..testMaster'
Set #add = 'Select address from ' + #table + ' where id = ' + CAST(#id AS VARCHAR(10)) + ' and name = ' + #name
Exec(#add)
END

How to pass output parameter to a Stored Procedure?

I have written a stored procedure with the following format:
ALTER PROCEDURE usp_data_migration
(#sourceDatabase varchar(50),
#sourceTable varchar(50),
#targetDatabase varchar(50),
#targetTable varchar(50),
#finaloutput varchar(max) output)
AS
BEGIN
----Set of SQL Blocks
END
Then, I am executing the procedure:
DECLARE #finaloutput1 varchar(300)
EXEC usp_data_migration 'Yousuf', 'emp', '[City Branch]', 'emp_tgt', #finaloutput1 output
SELECT #finaloutput1
By executing this way I don't proper output.
When I execute this way:
DECLARE #finaloutput1 varchar(300)
EXEC usp_data_migration #sourceDatabase = 'Yousuf',
#sourceTable = 'emp',
#targetDatabase = '[City Branch]',
#targetTable = 'emp_tgt',
#finaloutput1 output
SELECT #finaloutput1
I get an error message saying:
Msg 119, Level 15, State 1, Line 41
Must pass parameter number 5 and subsequent parameters as '#name = value'. After the form '#name = value' has been used, all subsequent parameters must be passed in the form '#name = value'.
And if I removed my output parameter and execute the procedure, I get my desired output but I am not able to get my result as an output.
EXEC usp_data_migration #sourceDatabase = 'Yousuf',
#sourceTable = 'emp',
#targetDatabase = '[City Branch]',
#targetTable = 'emp_tgt'
What should I do?
Thanks in advance.
The error message is self-explanatory - you should name all of your parameters.
DECLARE #finaloutput1 varchar(300);
EXEC dbo.usp_data_migration -- always use schema prefix
#sourceDatabase = 'Yousuf',
#sourceTable = 'emp',
#targetDatabase = '[City Branch]',
#targetTable = 'emp_tgt',
#finaloutput = #finaloutput1 OUTPUT;
SELECT #finaloutput1;
You have to Select like this
Example 1
create procedure p1
(
#id INT,
#name varchar(20) OUTPUT,
#company varchar(20) OUTPUT
)
AS
BEGIN
Set #name = 'name'
Set #company = 'company'
select #name , #company from table1 where id = #id;
END
GO
Example 2
CREATE PROCEDURE Myproc
#parm varchar(10),
#parm1OUT varchar(30) OUTPUT,
#parm2OUT varchar(30) OUTPUT
AS
SELECT #parm1OUT='parm 1' + #parm
SELECT #parm2OUT='parm 2' + #parm
GO
DECLARE #SQLString NVARCHAR(500)
DECLARE #ParmDefinition NVARCHAR(500)
DECLARE #parmIN VARCHAR(10)
DECLARE #parmRET1 VARCHAR(30)
DECLARE #parmRET2 VARCHAR(30)
SET #parmIN=' returned'
SET #SQLString=N'EXEC Myproc #parm,
#parm1OUT OUTPUT, #parm2OUT OUTPUT'
SET #ParmDefinition=N'#parm varchar(10),
#parm1OUT varchar(30) OUTPUT,
#parm2OUT varchar(30) OUTPUT'
EXECUTE sp_executesql
#SQLString,
#ParmDefinition,
#parm=#parmIN,
#parm1OUT=#parmRET1 OUTPUT,#parm2OUT=#parmRET2 OUTPUT
SELECT #parmRET1 AS "parameter 1", #parmRET2 AS "parameter 2"
go
drop procedure Myproc
Please refer more here
Simple Example:
create procedure proc2 #var int out,#var2 varchar(10) out
as
begin
set #var=(select max(id) from customer);
set #var2=(select name from customer where id=#var);
end
declare #maxid int;
declare #maxname varchar(10);
exec proc2 #maxid out,#maxname out;
select #maxid,#maxname;

How to set value to variable using 'execute' in t-sql?

DECLARE #dbName nvarchar(128) = 'myDb'
DECLARE #siteId int
exec ('SELECT TOP 1 #siteId = Id FROM ' + #dbName + '..myTbl')
select #siteId
When I run the script above I get the following error
Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "#siteId".
(1 row(s) affected)
Why and how to fix it?
Thank you
You can use output parameters with sp_executesql.
DECLARE #dbName nvarchar(128) = 'myDb'
DECLARE #siteId int
DECLARE #SQL nvarchar(max) = N'SELECT TOP 1 #outputFromExec = Id FROM ' + quotename(#dbName) + N'..myTbl'
exec sp_executesql #SQL, N'#outputFromExec int out', #siteId out
select #siteId
The dynamic SQL is a different scope to the outer, calling SQL: so #siteid is not recognised
You'll have to use a temp table/table variable outside of the dynamic SQL:
DECLARE #dbName nvarchar(128) = 'myDb'
DECLARE #siteId TABLE (siteid int)
INSERT #siteId
exec ('SELECT TOP 1 Id FROM ' + #dbName + '..myTbl')
select * FROM #siteId
Note: TOP without an ORDER BY is meaningless. There is no natural, implied or intrinsic ordering to a table. Any order is only guaranteed by the outermost ORDER BY
You can try like below
DECLARE #sqlCommand NVARCHAR(4000)
DECLARE #ID INT
DECLARE #Name NVARCHAR(100)
SET #ID = 4
SET #sqlCommand = 'SELECT #Name = [Name]
FROM [AdventureWorks2014].[HumanResources].[Department]
WHERE DepartmentID = #ID'
EXEC sp_executesql #sqlCommand, N'#ID INT, #Name NVARCHAR(100) OUTPUT',
#ID = #ID, #Name = #Name OUTPUT
SELECT #Name ReturnedName
Source : blog.sqlauthority.com
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Andrew Foster
-- Create date: 28 Mar 2013
-- Description: Allows the dynamic pull of any column value up to 255 chars from regUsers table
-- =============================================
ALTER PROCEDURE dbo.PullTableColumn
(
#columnName varchar(255),
#id int
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #columnVal TABLE (columnVal nvarchar(255));
DECLARE #sql nvarchar(max);
SET #sql = 'SELECT ' + #columnName + ' FROM regUsers WHERE id=' + CAST(#id AS varchar(10));
INSERT #columnVal EXEC sp_executesql #sql;
SELECT * FROM #columnVal;
END
GO
A slight change in the execute query will solve the problem:
DECLARE #dbName nvarchar(128) = 'myDb'
DECLARE #siteId int
exec ('SELECT TOP 1 **''#siteId''** = Id FROM ' + #dbName + '..myTbl')
select #siteId

Resources