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'
Related
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.
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
As it stands my colleague will be running the below query 30 times.
EXEC dbo.usp.Nameofstoredprocedure '01-nov-2016'
It exports 3 rows with columns ID, Name, type
Is there anyway to have it export as:
Date, ID, name, type
01-nov-2016,10,john smith,man
01-nov-2016,11,jane smith,woman
02-nov-2016,10,john smith, man
02-nov-2016,11,jane smith,woman
etc..
The stored procedure in question is not something I can copy and paste in due to policy.
Thinking it over, I can see a loop might work, possibly inserting the row into a table but I can't figure out how to do this, any assistance would be great.
Work so far:
declare #date date
set #date = '2016-11-01'
declare #inte int
while #inte >= 30
select * into #temp EXEC dbo.usp_GetMaxUsers #date
set #date = DATEADD(dd,1,#date)
set #inte = #inte + 1
Right now it's giving me the following error:
Msg 263, Level 16, State 1, Line 4
Must specify table to select from.
Msg 1038, Level 15, State 5, Line 4
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.
Thanks.
You could try this:
CREATE TABLE <Table Name>
(
Date DateTime,
ID INT,
Name NVARCHAR(40),
Type NVARCHAR(6)
)
INSERT INTO <Table Name>
Exec <SP NAME> 'Params'
You need to run the create table only once of course then put the rest into an agent job to run whenever you need it to.
The real problem is the stored procedure should be redone to meet the requirements. Database objects often need refactoring too.
I would add an enddate optional parameter (with a default value of null, so it won't break existing uses of the proc). Then if only the first date was sent in, it would set the end date to the correct value to get only records from that date. Otherwise it would use both dates in the internal query(ies) to get the information over a date range.
The answer that worked.
declare #date2 date
set #date2 = '2016-11-01'
declare #inte int=0
while #inte <= 29
begin
create table #temp
(
ID int,
Name varchar(100),
Type varchar(50)
)
insert into #temp
exec [dbo].[usp_proceduregoeshere] #date2
insert into #Results
select #date2, *
from #Agents
drop table #temp
set #date2 = dateadd(day, 1, #date2)
set #inte = #inte+1
end
select *
from #Results
I have a stored procedure that I pass 3 variables bankNumber, branchNumber and DateFrom to.
Based on these variables I want to query the table (seen in picture below stored procedure) to return all records that meet the criteria I pass (through variables).
Instead I am getting this error:
Conversion failed when converting date and/or time from character string
It seems to be failing when I pass it the DateFrom variable.
Thank you for your help
ALTER PROCEDURE [dbo].[Search_Records]
#bankNumber varchar(3),
#branchNumber varchar(3),
#dateCreated datetime
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
DECLARE
#Bank_Number varchar(3) = #bankNumber,
#Branch_Number varchar(3) = #branchNumber,
#DateFrom datetime = #dateCreated,
#DateTo datetime = #dateCreated
SELECT DISTINCT
A.bankNumber,
A.branchNumber,
A.dateCreated
FROM
dbo.CENSORED A
WHERE
(#Branch_Number IS NULL OR bankNumber LIKE #BankNumber + '%')
AND (#Branch_Number IS NULL OR branchNumber LIKE #Branch_Number + '%')
AND (#DateFrom IS NULL OR dateCreated LIKE + #DateFrom + '%')
AND (#DateTo IS NULL OR dateCreated LIKE + #DateTo + '%')
END
You cannot use the LIKE operator with Datetime value. If you are matching only on month you would need to use MONTH() function. LIKE operator can only be used with string data types.
Dont see the point of all these Variables declared in your stored procedure, a simplified version should look something like ....
ALTER PROCEDURE [dbo].[Search_Records]
#bankNumber varchar(3),
#branchNumber varchar(3),
#dateCreated datetime
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT
A.bankNumber,
A.branchNumber,
A.dateCreated
FROM
dbo.CENSORED A
WHERE
(#Branch_Number IS NULL OR bankNumber LIKE #bankNumber + '%')
AND (#Branch_Number IS NULL OR branchNumber LIKE #branchNumber + '%')
AND (#dateCreated IS NULL OR (MONTH(dateCreated) = MONTH(#dateCreated)
AND
YEAR(dateCreated) = YEAR(#dateCreated)))
END
Note
this will produce a very inefficient execution plan, consider using dynamic sql for queries with optional parameters like this one.
Using SQL Server 2012, and the new date type (not dateTime) I created the next procedure:
CREATE PROC Test(#StartDate date ,#EndDate date)
AS
DECLARE #Temp TABLE([ID] int, [Date] date)
INSERT INTO #Temp SELECT 1, CONVERT(date,'31/12/2012',103)
INSERT INTO #Temp SELECT 2, CONVERT(date,'01/10/2012',103)
INSERT INTO #Temp SELECT 3, CONVERT(date,'01/01/2012',103)
SELECT * FROM #Temp WHERE [Date] BETWEEN #StartDate AND #EndDate
When I run this stored procedure I get the next error indicating the date format of the parameter:
Incorrect syntax near '/'.
Please what should be done ?
For one, your date shouldn't have a / in it. But it also needs to be enclosed in quotes. Try:
EXEC dbo.Test #StartDate = '20120101', #EndDate = '20120131';
The reason it needs to be enclosed in quotes is, if you don't use quotes, your "date" is interpreted as a mathematical expression, e.g.:
01/01/2012 = 1 divided by 1 divided by 2012
The reason your date shouldn't have a / in it is because m/d/y and d/m/y are unsafe formats that can be interpreted differently depending on language and other settings.
And finally, if you are calling this procedure from C#, why are you passing strings and not properly typed parameters?