I want to pass the system date (GETDATE) only as a parameter in my SQL stored procedure. But I am getting an error while executing the procedure.
SQL query:
ALTER PROCEDURE ST_PRO_GETUSER
#D DATETIME = GETDATE --// passing GETDATE as a parameter.
AS BEGIN
select case when branch in ('A25','B10','C10')
then 'BR B1' Else 'BR B2'
end As [COLLECTION],FIXDATE
from MAIN_COUNTER where TDATE=#D --//Just want to pass date only
group by COLLECTION,FIXDATE
END
EXEC KK_SP_GETUSER_DIV
Error:
Conversion failed when converting date and/or time from character string.
What I have to do for it?
To pass as a parameter you just declare a variable and pass it in:
DECLARE #DATE DATETIME = GETDATE();
EXEC ST_PRO_GETUSER #DATE;
And if you want the date only, change the datatype of your parameter to a date and then do:
DECLARE #DATE DATE = GETDATE();
EXEC ST_PRO_GETUSER #DATE;
But part of your question seems to actually be asking how to specify a default parameter value. You can't use a function for the default value, so instead do:
CREATE PROCEDURE ST_PRO_GETUSER
(
#Date DATETIME = null
-- Change to DATE datatype if you don't want a time component.
-- #Date DATE = null
)
AS
BEGIN
SET NOCOUNT ON;
-- Default the #Date here is its null.
-- Note this doesn't handle the case when the caller wants to pass in null.
SET #Date = COALESCE(#Date,GETDATE());
-- SP Body
RETURN 0;
END
Solved My Self
ALTER PROCEDURE ST_PRO_GETUSER
#Date datetime = null
as
IF #Date is null
SET #Date = getdate() --// passing GETDATE as a parameter.
BEGIN
select case when branch in ('A25','B10','C10')
then 'BR B1' Else 'BR B2'
end As [COLLECTION],FIXDATE
from MAIN_COUNTER where TDATE=#D --//Just want to pass date only
group by COLLECTION,FIXDATE
END
EXEC ST_PRO_GETUSER
GETDATE() is the correct syntax, not GETDATE.
Related
I have a stored procedure which takes two parameters, #FromDate and #ToDate. But the #fromDate should be GetDate()-90. How can I pass the parameter value?
ALTER PROCEDURE spMyProcedure
#FromDate DATE,
#ToDate DATE
AS
BEGIN
// SQL statements
END
I want to execute it like this:
EXEC spMyProcedure #FromDate = GETDATE() - 60, #ToDate = GETDATE()
But it throws an error.
You can not do an alter/math/etc on a value passing to a stored procedure. You can declare a date above the stored procedure and then pass that value like this:
DECLARE #PassDate AS DATETIME
SET #PassDate = GETDATE() - 60
EXEC spMyProcedure #FromDate = #PassDate, #ToDate = GETDATE()
I suspect you are working with SQL Server if so, then use dateadd() function inside the stored procedure
set #FromDate = dateadd(day, -90, getdate())
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
I have one big SQL query and I want to pull out some data using that query
declare #Period VARCHAR(10) = 'MTD'
declare #Date DATETIME = '2011-08-31'
and I have a big select statement where I'm passing above parameters and it executes the output.
Now I have 10 different dates which I need to pass here each time to see the result.
How can I pass those date to above parameter declare #Date DATETIME how can I hard code it ?
So my desired output will be for those selected dates, give me hint for at least 3 dates ?
Use a table-valued parameter. First, create a type:
CREATE TYPE dbo.Dates AS TABLE(d DATE);
Now your stored procedure can take this type as a parameter:
CREATE PROCEDURE dbo.whatever
#d dbo.Dates READONLY
AS
BEGIN
SET NOCOUNT ON;
SELECT t.columns
FROM dbo.tableName AS t
INNER JOIN #d AS d
ON t.[date] = d.d;
END
GO
Then from your application you can pass this parameter in as a DataTable, for example.
I'm trying to get the current date into a variable inside a SQL stored procedure using the following commands
DECLARE #LastChangeDate as date
SET #LastChangeDate = SELECT GETDATE()
This gives me the following error: "Incorrect Syntax near 'SELECT'"
This is the first stored procedure I've ever written, so I'm unfamiliar with how variables work inside SQL.
You don't need the SELECT
DECLARE #LastChangeDate as date
SET #LastChangeDate = GetDate()
Just use GetDate() not Select GetDate()
DECLARE #LastChangeDate as date
SET #LastChangeDate = GETDATE()
but if it's SQL Server, you can also initialize in same step as declaration...
DECLARE #LastChangeDate date = getDate()
DECLARE #LastChangeDate as date
SET #LastChangeDate = GETDATE()
SELECT #LastChangeDate = GETDATE()
You can also use CURRENT_TIMESTAMP for this.
According to BOL CURRENT_TIMESTAMP is the ANSI SQL euivalent to GETDATE()
DECLARE #LastChangeDate AS DATE;
SET #LastChangeDate = CURRENT_TIMESTAMP;
I have a stored procedure which update a table based on such calculation and the calculation is done as column name (Calendatedate) - (Current System Date Time) and update this information to a column (TimeSpent) and display the value in Hh:Mm:SS:Msec format.
The query is working fine but I want to update it in such a way so that the time spent should be only HH:MM:SS format. Please help me that how I remove that Msec from the time spent.
CREATE procedure St_Proc_UpdateTimeSpent
#timeEntryID int,
#status int output
as begin
set nocount on;
declare #Date dateTime;
set #Date=GETDATE();
update Production set TimeSpent=(SELECT CONVERT(VARCHAR(20),DateAdd(SS,Datediff(ss,CalendarDate, #Date)%(60*60*24),0),114)),
IsTaskCompleted=1
where productionTimeEntryID=#timeEntryID
set #status=1;
return #status;
end
You can just use style 108 instead of 114 in the CONVERT function to get only the hh:mm:ss:
CREATE PROCEDURE dbo.St_Proc_UpdateTimeSpent
#timeEntryID int,
#status int output
AS BEGIN
SET NOCOUNT ON;
DECLARE #Date DATETIME;
SET #Date = GETDATE();
UPDATE dbo.Production
SET TimeSpent = CONVERT(VARCHAR(20), DATEADD(SS, DATEDIFF(ss, CalendarDate, #Date)%(60*60*24),0), 108),
IsTaskCompleted = 1
WHERE
productionTimeEntryID = #timeEntryID
SET #status = 1;
RETURN #status;
END
See the excellent MSDN documentation on CAST and CONVERT for a comprehensive list of all supported styles when converting DATETIME to VARCHAR (and back)
BTW: SQL Server 2008 also introduced a TIME datatype which would probably be a better fit than a VARCHAR to store your TimeSpent values ... check it out!