Executing one stored-procedure from another throws error - sql-server

My Stored procedure is like this
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE ph_GetAllStaffAddressByCamp
#Year INT,
#strYear VARCHAR(2) OUTPUT
AS
IF NULLIF(#Year, '') IS NULL
SET #Year = Exec [cs_GetCurrentYear] #strYear
SELECT DISTINCT [VolID], [CampID], [VolFName] FROM [vStaffJobAndCamp]
where CampCode Like #Year
As you can see I am trying to execute [cs_GetCurrentYear] inside this procedure (added the procedure below)
ALTER PROCEDURE [dbo].[cs_GetCurrentYear]
#strYear VARCHAR(2) OUTPUT
AS
SELECT #strYear = Year FROM tblCurrentYear
But this throws an error on compile .
And it looks like this
Msg 156, Level 15, State 1, Procedure ph_GetAllStaffAddressByCamp, Line 8
Incorrect syntax near the keyword 'Exec'.

You can create a table, and insert into it the result of your SP. Try
DECLARE #TheYear TABLE
(
TheYear Varchar(2)
)
INSERT INTO #theYear (TheYear)
Exec [cs_GetCurrentYear] #strYear
SET #Year = (SELECT TOP(1) TheYear FROM #TheYear)

You can modify your second stored procedure to a stored function and call it from your first stored procedure. Read more here: How to call a scalar function in a stored procedure

Related

Problem with adding procedure and error with invalid object name

My first question: How to add the following procedure to the "Programmability-> Stored Procedures" folder.
USE [Tournaments]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spPrizes_Insert]
#PlaceNumber int,
#PlaceName nvarchar(50),
#PrizeAmount money,
#PrizePercentage float,
#id int = 0 output
AS
BEGIN
SET NOCOUNT ON;
insert into dbo.Prizes (PlaceNumber, PlaceName, PrizeAmount, PrizePercentage)
values (#PlaceNumber, #PlaceName, #PrizeAmount, #PrizePercentage);
select #id = SCOPE_IDENTITY();
END
and second question - I have error:
Msg 208, Level 16, State 6, Procedure spPrizes_Insert, Line 9
Invalid object name 'dbo.spPrizes_Insert'.
Why?

Copy column from one table to another table with condition

ALTER PROCEDURE [dbo].[Timesheet_update]
AS
BEGIN
DECLARE #sql2 nvarchar(max), #status nvarchar(1)
SET #sql2 = 'insert into s21022020 (s21_stfno) select m_stfno from master where m_status<>'D''
EXECUTE (#sql2)
END
EXECUTE Timesheet_update
Results in an error:
Msg 207, Level 16, State 1, Line 23
Invalid column name 'D'.
m_status column contain data =D
I don't understand why you feel the need to make this a dynamic SQL - just write the statement directly inside the stored procedure - like this:
ALTER PROCEDURE [dbo].[Timesheet_update]
AS
BEGIN
INSERT INTO s21022020 (s21_stfno)
SELECT m_stfno
FROM master
WHERE m_status <> 'D'
END

SQL stored procedure - table as parameter

I have a database with different tables (all the same structure) where I'd like to run a stored procedure having a parameter that defines which table to query.
I can't seem to figure it out:
CREATE SCHEMA test;
GO
First I created a schema
CREATE TYPE DataType as TABLE (
[datetime] [datetime] NULL,
[testVar] [bigint] NULL)
GO
Then I created the table type
USE [TestDataFiles]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [test].[testing]
(
-- Add the parameters for the stored procedure here
#datetime datetime,
#t DataType READONLY
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
select top(10) *
from #t
where [datetime] > #datetime
END
GO
Then I created the stored procedure.
Exec test.testing #t = 'table.1', #datetime = '2017-01-01'
However when I call it I get the following error:
Msg 206, Level 16, State 2, Procedure test, Line 0 [Batch Start Line 0]
Operand type clash: varchar is incompatible with DataType
Same happens with:
Exec test.testing #t = [table.1], #datetime = '2017-01-01'
I have seen an example where in the procedure between the begin and select you put something like:
INSERT INTO table.1
( datetime, testVar)
But table.1 (or table.2 etc as I have a list of tables) has data and I don't want to change it.
Unless I'm meant to create a dummy table like I did the TYPE?
The examples I've found online havent been useful.
To do that you will need to use dynamic SQL
The basic procedure is to build up a string that will hold the statement you will execute, then execute it
declare #SQL nvarchar(1000)
declare #t as nvarchar (1000)
set #t = 'MyTable'
set #Sql = 'Select * from ' + #t
exec sp_executesql #sql
You have to pass parameter of type DataType. So, create variable of that type and pass it into stored procedure like
declare #table1 DataType
INSERT INTO #table1(datetime, testVar) values (..., ...)
Exec test.testing #datetime = '2017-01-01', #t = #table1

not able to declare variable as TVP type in Stored Proc

I have created a TVP and I am trying to use it in a stored proc for my input into stored proc.
the issue is I am not able to create my SP with it. Its says
Msg 137, Level 16, State 1, Procedure uspGetUsersPresentCount, Line 14
Must declare the scalar variable "#usersList".
My SP is
IF EXISTS (SELECT * FROM sysobjects WHERE name = 'uspGetUsersPresentCount')
BEGIN
DROP Procedure [AMProcedures].[uspGetUsersPresentCount]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [AMProcedures].[uspGetUsersPresentCount]
(
#usersList AS [AMProcedures].[udfUserListTVP] READONLY,
#startDate DATETIME,
#endDate DATETIME
)
AS
BEGIN
DECLARE #okStatus TINYINT = 4
SET NOCOUNT ON
SELECT MIMO.UserID, COUNT(MIMO.MoveInTime) FROM AMTables.tblUserMoveInMoveOutDetails MIMO
JOIN #usersList ON MIMO.UserID=#usersList.UserID
WHERE MIMO.Status=#okStatus AND
MIMO.MoveInTime BETWEEN #startDate AND #endDate
GROUP BY MIMO.UserID
SET NOCOUNT OFF
END
GO
can anyone tell me what wrong am I doing ...I have tried what I knew, but nothing seems to work.
Thanks in advanced.
Either use an alias for the user list, or put it in square braces:
JOIN #usersList UL ON MIMO.UserID=UL.UserID
or
JOIN #usersList ON MIMO.UserID=[#usersList].UserID

How to call a stored procedure and return a value?

Hey all,
I have a stored procedure and I need to call it within another stored procedure, but I want the first one to return a value (field value).
CREATE PROCEDURE rnd_STR
(
#Length int
)
#alphaVar varchar(10) OUTPUT
AS
SET #alphaVar = 'blah'
#procedure body
END
GO
DECLARE #alphaVar varchar(10)
EXEC rnd_STR #alphaVar output
SELECT #alphaVar
ERRORS
Msg 102, Level 15, State 1, Procedure rnd_STR, Line 6
Incorrect syntax near '#alphaVar'.
Msg 137, Level 15, State 1, Procedure rnd_STR, Line 8
Must declare the scalar variable "#alphaVar".
Msg 2812, Level 16, State 62, Line 4
Could not find stored procedure 'rnd_STR'.
(1 row(s) affected)
didn't work !!
How can I call it??
BTW, the returned #ID is a string
You say #alphaVar is varchar(10). In that case you need to use an output parameter as below. Return can only be used for integer types in stored procedures.
CREATE PROCEDURE rnd_STR
#Length int,
#alphaVar varchar(10) OUTPUT
AS
BEGIN
SET #alphaVar = 'blah'
/* Rest of procedure body*/
END
GO
DECLARE #alphaVar varchar(10)
EXEC rnd_STR 10, #alphaVar output
SELECT #alphaVar
Alternatively you could use a scalar UDF rather than a stored procedure.
You're calling syntax is wrong.
DECLARE #newId int
EXEC #newId = rnd_STR, #length = 10
See EXECUTE in the reference.
Try this:
EXEC #alphaVar = rnd_STR 10
A work around of getting this code is to execute the stored procedure in your Management Studio itself and copy the SQL code

Resources