T-SQL - dynamic parameter in stored procedere [duplicate] - sql-server

This question already has an answer here:
Stored Procedure parameter default value - is this a constant or a variable
(1 answer)
Closed 4 years ago.
Is there a way to use dynamic date parameter in a stored procedure between CREATE PROCEDURE and BEGIN?
CREATE PROCEDURE dbo.MYSP
#StartDate DATETIME = GETDATE(),
#EndDate DATETIME = GETDATE() - 1
BEGIN
AS
Is this possible?

You can't add GETDATE() default parameter to stored procedure. Instead of this you can do this :
DROP PROCEDURE dbo.MYSP
GO
CREATE PROCEDURE dbo.MYSP
#StartDate DATETIME = NULL,
#EndDate DATETIME = NULL
AS
BEGIN
IF #StartDate IS NULL SET #StartDate=GETDATE()
IF #EndDate IS NULL SET #EndDate=DATEADD(DAY, -1, GETDATE())
SELECT #StartDate,#EndDate
END
GO
dbo.MYSP

Related

SQL Server stored procedure oDate as a parameter not recognized

How can we pass the date (data type DateTime) in the execution command to run a stored procedure?
Here is the code snippet.
ALTER PROCEDURE [dbo].[datefiltered]
#months_margin int,
#oDate datetime
AS
BEGIN
SELECT *
FROM dbo.table20
WHERE date = oDate
-- more code...
END
I am trying to execute this stored procedure using GETDATE() function or even pass date and time as a string but it's not working.
exec datefiltered 23 getDate()
As you want to apply date filter, you don't need to pass datetime value. You can convert to DATE datatype for equality.
select * from dbo.table20
where date = CAST(#oDate AS DATE)
Also, if you are just passing GETDATE() as default, you can keep getdate as default value, as given below:
Alter procedure [dbo].[datefiltered]
#months_margin int,
#oDate datetime = null
AS
Begin
IF #oDate IS NULL
BEGIN
SET #oDate = CAST(GETDATE() AS DATE)
END
When you call the procedure with default value, you don't need to pass parameter value for it.
exec datefiltered 23 -- getdate() filter is applied automatically
ALTER PROCEDURE [dbo].[datefiltered]
#months_margin int,
#oDate datetime
AS
BEGIN
SELECT *
FROM dbo.table20
WHERE date = CAST(#oDate AS DATE)
-- more code...
END
Executing this stored procedure:
exec datefiltered 23, '2010-02-30'

Use GetDate() as default parameter for SP in T-SQL not working

I am trying to create a SP in TSQL that gets month as parameter (in numeral format). I would like that if the parameter be suppressed by the user then the SP will use the current month.
I tried this but it says that I am using an incorrect syntax:
CREATE PROCEDURE myproc
#month int = select Month(GetDate())
What am I doing wrong?
Thanks!
You cannot pass func call as default parameter value:
CREATE PROCEDURE myproc
#month int = select Month(GetDate())
should be:
CREATE PROCEDURE myproc
#month int = NULL
AS
BEGIN
SET #month = COALESCE(#month, Month(GetDate()));
SELECT #month;
END;
db<>fiddle demo
If user does not provide value for #month then by default it is NULL and COALESCE will set proper value.

Why does T-SQL print statement cause ResourceClosedError: This result object does not return rows. It has been closed automatically

I'm calling a SQL Server SP from Jupyter, and the SP looks like this:
ALTER
procedure [dbo].[proc_Report_QuarterlyDistribution02] (#quarter int, #year int, #group int)
as
declare #total int,
#date date
set #date = cast(#year as varchar(4)) + '-01-01'
set #date = dateadd(quarter, #quarter - 1, #date)
print #date
select #total = count(1)
from DimMedical
where ServiceDate between
DATEADD(quarter, -9,#date) and #date
and carriercode = #group
and Category = 'Physicians'
The SP goes on - that's not the issue.
The problem is the line
print #date
Question Why would the print statement cause the error:
ResourceClosedError: This result object does not return rows. It has been closed automatically.
Why would the print statement cause the error: "This result object does not return rows"
This is probably a limitation in the client library you are using. Some client libraries stop looking for a result set when they see a message.
Either remove the print statement, upgrade your client library (not mentioned), or have the stored procedure insert into a table using INSERT … EXEC, and then select from that in a subsequent query.

stored procedure confusing named parameters 'Error converting data type nvarchar to int.'

Running the exact same sql command, I get an error depending on what order the parameters are defined in the stored proc. This error was originally encountered using a stored proc mapped through entity framework, but that does not seem to be the cause of the issue.
The error message 'Error converting data type nvarchar to int.' makes it seem like the sproc is trying to jam the #CagIdList parameter into one of the nullable int parameters. Thoughts?
Sql command:
exec sp_executesql
N'rptAll.usp_SprocParameterTest #StartDate, #EndDate, #CAGIdList',
N'#StartDate datetime,#EndDate datetime,#CAGIdList nvarchar(1317)',
#StartDate='2014-11-16 00:00:00',#EndDate='2014-12-16 00:00:00',#CAGIdList=N'857,858,859'
The above command will fail with this stored proc:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [rptAll].[usp_SprocParameterTest]
(
#StartDate datetime,
#EndDate datetime,
#StartRow int = null, -- please note where this parameter started
#MaxRows int = null, -- me too
#Sort varchar(255)= null,
#mfgCode varchar(255) = null,
#CAGIdList varchar(max) = null
)
as
select 1
The same will succeed for this stored proc :
--Move the nullable int params to the end of the list
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [rptAll].[usp_SprocParameterTest]
(
#StartDate datetime,
#EndDate datetime,
#Sort varchar(255)= null,
#mfgCode varchar(255) = null,
#CAGIdList varchar(5000) = null,
#StartRow int = null, --look at mee
#MaxRows int = null --hey me too
)
as
select 1
That's because you are calling the procedure and providing values for the three first parameters, regardless of their names. The parameter names that you use in the query have no relation to the parameter names in the procedure.
If you want to specify parameter values for specific parameters, you have to name them:
rptAll.usp_SprocParameterTest #StartDate = #StartDate, #EndDate = #EndDate, #CAGIdList = #CAGIdList
This is the same difference as calling a procedure without parameter names:
rptAll.usp_SprocParameterTest '2014-11-16 00:00:00', '2014-12-16 00:00:00', N'857,858,859'
and with parameter names:
rptAll.usp_SprocParameterTest #StartDate = '2014-11-16 00:00:00', #EndDate = '2014-12-16 00:00:00', #CAGIdList = N'857,858,859'

T-SQL - get date by dynamic params

I tried to figure out a dynamic query to get date col within past 20 days. The idea is quite simple and, moreover, I know the table does contain dates from getdate() to -20 days but still no result get returned
DECLARE #date_past_period varchar(MAX);
DECLARE #date_past_number varchar(MAX);
SET #date_past_period='day';
SET #date_past_number='20';
DECLARE #aDate datetime;
DECLARE #sql varchar(MAX);
SET #sql='SELECT date FROM table WHERE convert(varchar,date,121) BETWEEN convert(varchar,getdate(),121) AND convert(varchar,dateadd('+#date_past_period+', -'+#date_past_number+', getdate()),121)';
exec(#sql);
Maybe the problem is in dynamic thing but I am not sure.
Any useful comment is appreciated
You can use CASE function (T-SQL):
CREATE PROCEDURE MyStoredProcedure
#IntervalType VARCHAR(15),
#Num INT
AS
DECLARE #StartDate DATETIME = GETDATE();
DECLARE #EndDate DATETIME =
CASE #IntervalType
WHEN 'DAY' THEN DATEADD(DAY,#Num,#StartDate)
WHEN 'MONTH' THEN DATEADD(MONTH,#Num,#StartDate)
WHEN 'YEAR' THEN DATEADD(YEAR,#Num,#StartDate)
END;
IF #EndDate IS NULL
RAISERROR('Invalid params', 16, 1);
ELSE
SELECT date FROM table WHERE date BETWEEN #StartDate AND #EndDate;
By converting to VARCHAR your search condition from WHERE will not be SARG ( 1 & 2 ).
I am pretty sure this scenario can be covered without using dynamic SQL, however, one obvious problem in your SQL is the between clause - the range is in the wrong order. Try changing your #sql as below:
SET #sql='SELECT date FROM table WHERE convert(varchar,date,121) BETWEEN convert(varchar,dateadd('+#date_past_period+', -'+#date_past_number+', getdate()),121) AND convert(varchar,getdate(),121)';

Resources