Change variable within SQL Server stored procedure - sql

I'm running a simple while loop that executes a stored procedure given a condition. Is there any way to access the stored procedure variable and change a variable within it before it executes? The variable I want to change is the same as the #date variable.
Thanks for any help guys.
declare #dayscount int
Declare #date as date
set #dayscount = 256
set #date = cast(GETDATE() - #dayscount as Date);
while (#dayscount >= 1)
exec A
set #dayscount = #dayscount - 1

You can try recursion in a CTE if all you are doing is decrementing or dynamic sql within your stored procedure and the replace function to replace the variable with the values you want and then run the execute_sql stored procedure within your stored procedure.

Related

A stored procedure returns multiple values but only need one

I'm trying to build a stored procedure that seems to return a grid. But I only need the first column of that grid. Below is the code I'm using to call the procedure
USE [OperationsView]
DECLARE #ProductionDate As DateTime
DECLARE #tag_in As VARCHAR(80)
DECLARE #FCChemGALPERMIN float
DECLARE #pi_server As VARCHAR(32)
DECLARE #endDate As DateTime
DECLARE #Debug As Bit
DECLARE #result As Float
SELECT #ProductionDate = '2016-12-01 07:00:00'
SELECT #tag_in = 'I-FC-835'
SELECT #pi_server = 'valpi'
SELECT #endDate = DATEADD(DAY, 1, #productionDate)
SELECT #Debug = 1
EXEC #FCChemGALPERMIN = Interface.proc_GetPIValueAverageTime
#result, #tag_in, #ProductionDate, #endDate, #pi_server, #Debug
PRINT #FCChemGALPERMIN
PRINT 'done'
Under the results tab I need that float value, I don't care about the percentage next to it. Below this picture is what I get from the messages tab. Basically I want to grab that float value and assign it to a variable so I can display it in the messages tab also.
Results tab looks like this:
Messages tab looks like this:
The ChemGALPERMIN displays 0 when I simply print that variable. What do I do to get desired float number?
If Interface.Proc_getpivalueaveragetime is a stored procedure and NOT a user defined function, then you CANNOT return a value from stored procedure like that.
UPDATE: if you are sure that your stored procedure will ALWAYS return only 1 float value and the stored procedure doesn't update physical tables data, then you can convert it to a user defined function (CREATE FUNCTION examples) then you will be able to use it the way you have it in your original post, i.e. #result = Interface.Proc_GetPIvalueAverageTime(...) .
But if you still want to keep it as a stored procedure call then you need to pass an additional parameter to Interface.Proc_GetPIValueAverageTime and mark it as OUTPUT. Then in the body of your stored procedure, probably in the end of it when you already have the needed float value, you need to set that additional OUTPUT param to the calculated float value.
So, in code it will look something like this (you need to update your stored procedure definition):
CREATE PROCEDURE Interface.proc_GetPIValueAverageTime
#result float,
#tag_in varchar(80),
#ProductionDate DATETIME,
#endDate DATETIME,
#pi_server VARCHAR(32),
#Debug bit,
-- new param below
#sproc_result float OUTPUT
AS
BEGIN
... do your calc ..
set #sproc_result = #calculation_result_as_float
END
Then in the calling context you need to define that extra result var (or use the one you already have called #result ) and pass that extra param to the stored procedure call:
declare #sproc_result float;
EXEC #FCChemGALPERMIN = Interface.proc_GetPIValueAverageTime
#result, #tag_in, #ProductionDate, #endDate, #pi_server, #Debug,
#sproc_result OUTPUT
-- here #sproc_result will have the float value you've assigned to it in the stored procedure body.
print cast(#sproc_result as varchar(15))
Note, IIRC you need to specify OUTPUT after the returning param both in the stored procedure definition and in the calling statement.
Note, you're already passing the #result var as the first param into your stored procedure. then just add OUTPUT modifier to it both in the stored procedure definition and calling statement and assign the value to it in the stored procedure body. This way you won't need the new stored procedure param which I've named #sproc_result.
HTH
Considering there is a need for second column some where else.
Insert the result into temp table and take the float value from there
Insert into #temp(float_col,percent_col)
EXEC Interface.Proc_getpivalueaveragetime
#result,
#tag_in,
#ProductionDate,
#endDate,
#pi_server,
#Debug
select #FCChemGALPERMIN= float_col
From #temp
If your second column is not useful at any case then alter your procedure from resulting percentage column

"Must declare the scalar variable" error when executing a stored procedure

I have tried to make a procedure to insert a price:
create procedure prInsertPrice
#NuggetID varchar(5),
#Unit_Price money,
#Start_Date datetime,
#End_Date datetime
as
begin
DECLARE #date AS DATETIME
SET #date = GETDATE()
if
(
(#NuggetID like 'N[0-9][0-9]')
and
(#Unit_Price is not null)
and
(#Start_Date is not null)
)
begin
print 'Insert Success'
insert NuggetPrice (NuggetId, Unit_Price, Start_Date, End_Date)
values (#NuggetID, #Unit_Price, #Start_Date, #End_Date)
end
else
begin
print 'Failed to insert'
end
end
When I execute the procedure it's fine, but when I run the procedure like this:
EXEC prInsertPrice 'N01', 20000, #date, null
I get the error message:
Must declare the scalar variable #date.
Why is this and how can I correct the problem?
The #date in the exec statement is different then the one in the stored proc.
You should do something like:
DECLARE #date AS DATETIME
SET #date = GETDATE()
EXEC prInsertPrice 'N01', 20000, #date, null
When you run:
EXEC prInsertPrice 'N01', 20000, #date, null
You are passing the variable #date as the third parameter to your stored procedure, as #Start_Date. This is entirely separate from the #date variable which you have declared inside the stored procedure itself, which gets declared and initialised after the procedure has been called, as it executes.
If you have not initialised the #date variable which is being passed as a parameter to the stored procedure before calling the stored procedure, then you will get the error you have described.
So, you need to declare and initialise this variable first:
DECLARE #date DATETIME = '2017-01-01' -- You can whatever date value you require here
EXEC prInsertPrice 'N01', 20000, #date, null
This should prevent the error.
Note: You can also separate the declaration and initialisation of the #date variable if you would prefer:
DECLARE #date DATETIME
SET #date = '2017-01-01'
In addressing your underlying problem though or preventing bad data being inserted into your NuggetPrice table though, I would agree with Prdp's suggestion of adding a CHECK Constraint to the table, for example:
ALTER TABLE NuggetPrice
ADD CONSTRAINT CK_NuggetPrice CHECK (NuggetID LIKE 'N[0-9][0-9]'
AND Unit_Price IS NOT NULL
AND Start_Date IS NOT NULL)
This would also prevent anyone from inserting records which do not agree with the logic specified.
Already other two answers gave enough information on the reason for error so am not going to talk about it. Here is different approach to solve the data validation
Instead of creating a Stored Procedure to restrict inserting bad data into table, I would suggest you to create a Check constraint to do this
ALTER TABLE NuggetPrice
ADD CONSTRAINT CK_NuggetPrice CHECK (NuggetID LIKE 'N[0-9][0-9]' AND Unit_Price IS NOT NULL AND Start_Date IS NOT NULL)
This will make sure nobody inserts bad data in NuggetPrice

GETDATE scalar variable

I'm retrieving a must declare scalar variable error for #StartFixtureDay but not sure what I need to do or see the problem with my code:
CREATE PROCEDURE [dbo].[Date_Insert]
AS
SET NOCOUNT ON
BEGIN
DECLARE #StartFixtureDay DATE
SET #StartFixtureDay = CAST(GETDATE() AS DATE)
;WITH League_Dates AS (
...
SELECT rn,
week_number,
DATEADD(day, week_number - 1, #StartFixtureDay) AS WeekNumber,
...
... The exec below is on a separate page
EXEC [dbo].[Date_Insert] #StartFixtureDay
You must declare #StartFixtureDay as parameter on the stored procedure
CREATE PROCEDURE [dbo].[Date_Insert] (#StartFixtureDay date)
AS
...
The procedure is not defined as having a parameter yet you are passing one.
You need to put the parameter into the procedure definition before you can pass it
You have declared #StartFixtureDay INside of your stored procedure.
When you call EXEC you are OUTside of your procedure.
And this OUTside code does'nt know about INside variables.
declare your variable before EXEC and declare parameters in your procedure
CREATE PROCEDURE [dbo].[Date_Insert] (#ParamName DATE)
AS
DECLARE #StartFixtureDay DATE
SET #StartFixtureDay = #ParamName
...
...
DECLARE #OutsideVriable DATE
SET #OutsideVriable = CAST(GETDATE() AS DATE)
EXEC [dbo].[Date_Insert] #OutsideVariable
As you above all suggest based on your execution procedure, your datatime parameter need to define.
Also you are written wrong, please correct as
CREATE PROCEDURE [dbo].[Date_Insert]
AS
SET NOCOUNT ON
BEGIN
DECLARE #StartFixtureDay DATE
SET #StartFixtureDay = ( Select CAST(GETDATE() AS DATE)) --direct cast not work, need to select keyword

SQL Server Stored Procedure capture return value in T-SQL

I have a SQL Server stored procedure; I need to capture the return value from the stored procedure. Is this the correct way of doing this?
declare valback varchar(30)
set valback = exec storeproc1
In this case, storeproc1 is my stored procedure.
To start, use proper T-SQL syntax:
declare #valback int;
exec #valback = storeproc1;
The only return type allowed for a stored procedure is int. Stored procedures return status via the return statement.
I somehow have a feeling that you really want something else, namely:
to have an OUTPUT parameter in the procedure:
declare #valback varchar(30);
exec storedproc1 #valback OUTPUT;
or capture the procedure result set via INSERT ... EXEC. See How to Share Data Between Stored Procedures.
The correct syntax is:
DECLARE #valback VARCHAR(30)
EXEC #valback = storeproc1
As per the documentation:
http://msdn.microsoft.com/en-us/library/ms188332.aspx

SQL Returning a datetime from a procedure results in Implicit conversion error

I'm fairly new to SQL and was trying to write a procedure that would check a passed in value and set a local datetime variable and then return that variable.
USE [MyDB]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [Common].[Update_Date]
#Status_ID int
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Date_Value DATETIME
IF #Status_ID = 2
SET #Date_Value = GETDATE()
ELSE
SET #Date_Value = NULL
RETURN #Date_Value
END
GO
When I try to execute this script I get the following error:
Msg 257, Level 16, State 3, Procedure Update_Date, Line 19
Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query.
Is it trying to do something with my #Status_ID parameter?
Stored procedures return values by using OUTPUT parameters:
CREATE PROCEDURE [Common].[Update_Date]
#Status_ID int,
#Date_Value DATETIME OUTPUT
AS
BEGIN
SET NOCOUNT ON;
IF #Status_ID = 2
SET #Date_Value = GETDATE()
ELSE
SET #Date_Value = NULL
END
GO
When invoked from ADO.Net, you use ParameterDirection.Output. From T-SQL you invoke with an OUTPUT clause:
declare #date DATETIME;
exec [Common].[Update_Date] 2, #date OUTPUT;
SELECT #date;
In general is better not to mix procedure output with the return and with the result set (so that would be a vote against most other recommendation you got to use SELECT). Using OUTPUT makes procedures reusable from other T-SQL code, using result set (SELECT) makes it much harder to use as T-SQL has problems capturing the result set of an invoked procedure (you'd have to use INSERT ... SELECT and deal with all the problems that has).
RETURN values in Stored Procedures can only be integers. Therefore youre getting an error converting #Date_Value to an int
It looks like you need a Function, not a Stored Procedure
CREATE FUNCTION (Transact-SQL)
Alternatively, you can change RETURN to SELECT, but I would recommend using a FUNCTION for this type of request.
The return value from a stored procedure must be an integer. The RETURN #Date_Value line is throwing the error.
I believe the return value of a stored procedure is an integer, and your return statement is converting the datetime to int. Can you do a select instead to return the value?
SELECT #Date_Value
Here is a link on return values, output values, and result sets that you might find useful:
http://sqlserverpedia.com/wiki/Stored_Procedures_-_Output_Parameters_%26_Return_Values
You don't have to use "return" to return a value, you use "select" to return the value. Just change the RETURN keyword at the end of your SP and use SELECT and i will work.
The Return keyword must be used to return an integer. Try changing it to Select #Date_Value
You had a few problems. Try this:
CREATE PROCEDURE [Common].[Update_Date](
#Status_ID INT
) AS
SET NOCOUNT ON
BEGIN
--will #Date_Value have an initial value of NULL????
DECLARE #Date_Value DATETIME
SET #Date_Value = NULL
IF #Status_ID = 2 BEGIN
SET #Date_Value = GETDATE()
END
SELECT #Date_Value
END