Convert Parameter Value Form DateTime To Int32 - sql

I am having problems with a Stored Procedure I am writing.
I am gathering data from a number of tables, most of which hold a date value, but one holds just a month(int)
I declare the following Parameters at the beginning of my SP.
#FromDate DateTime,
#ToDate DateTime
This works fine for most of my tables, but for the table where I am just requiring the Month from the #FromDate, I run into the following error:
"Failed to convert parameter value form a DateTime to a Int32."
Here is my Select statement for the Problem Table:
SELECT Branch, Discount
FROM MonthlyPromotions
WHERE (Month = DATEPART(mm,#FromDate))
Also, in the MonthlyPromotions Table the Month Field is an Int.
Can anyone help on this ASAP??
Thankyou

To troubleshoot your problem, can you do a
PRINT CAST(CAST(DATEPART(mm, #FromDate) AS INT) AS VARCHAR(50))
RETURN
At the beginning of your SP?
If that doesn't give an error, you can proceed to:
SELECT Branch, Discount
FROM MonthlyPromotions
WHERE Month = CAST(DATEPART(mm,#FromDate) AS INT)

select cast(getdate() as int)

Related

Convert date string to date sql server

I have a table tbl with column cln varchar(50).
Data is stored in format 'January-2008', February-2009, March-2010 etc(full month name)
I want to convert it to date (for comparison, sort etc).
please try below query
DECLARE #v varchar(20)
SET #v='January-2008'
SELECT CAST('01-'+#V as DATE)
Since you don't get the day data and only -, we'll add '01-' to complete the date day part.
sql fiddle link: http://sqlfiddle.com/#!6/6f326/7
Use Convert with Style to avoid errors in different date settings
DECLARE #v varchar(20)
SET #v='January-2008'
SELECT CONVERT(DATETIME,'01-'+#v,13)

How to compare smalldatetime in stored procedure

I'm writing stored procedure to compare dates but it's not working properly. How can I make it so it compares only the dates but not the time? What I'm trying to do is compare the times and if the Id is null than insert a new entry with the same name but new time. I'm keeping multiple entries with same name but different test time.
ALTER PROCEDURE [dbo].[UL_TestData]
(
#Name varchar(30),
#Test_Time smalldatetime,
#ID INT output
)
AS
Declare #UpdateTime smalldatetime
SELECT #ID=ID FROM Info_User WHERE Name=#Name AND UpdateTime= #Test_Time
IF(#ID IS NULL)
BEGIN
INSERT INTO Info_User (Name, UpdateTime) VALUES (#Name, #UpdateTime)
END
there are a lot of solutions to this depending on what type of DBMS, however here is one:
SELECT #ID=ID FROM Info_User WHERE Name=#Name AND floor(cast(#UpdateTime as float))= floor(cast(#Test_Time as float))
this works because smalldatetime's date is stored a whole numbers, where the time is stored as decimals.
I would cast the dates to a plain date which makes this solution independent of implementation details
select #ID=ID
from info_user
where Name = #Name
and cast (UpdateTime as Date) = Cast(#TestTime as Date)
However, I would either add the date part of the UpdateTime as an additional (calculated) column or split the information into a date and a time part. This makes it much easier to query entries by the plain date.
As a rule of thumb: The type of columns (in general: the table layout) greatly depends on the type of query you usually run against your data.
Edit: As attila pointed out, the date datatype only exists in version 2008 and up

using LIKE and BETWEEN in sql query

alter PROCEDURE [dbo].[select_User_attendance_master_Date]
(
#From_date NVarchar(100),
#To_date NVarchar(100)
)
as
begin
select
Employee_Attendace_Code,
Convert(varchar(11),Employee_Attendance.Attendance_day,106) as Attendanceday
from Employee_Attendance
(Convert(varchar(11),Employee_Attendance.Attendance_day,106) between '%'+#From_date+'%'
AND '%'+#To_date+'%')
end
this query is not working it is getting nothing in Attendance_day values are eg 2013-11-28
Please rethink your question.
LIKE is great to operate over strings but ill not work well for dates.
depending on your data it can return a from date is greater than to date.
Try to use date/datetimes variables, if you receive dates as a string, convert that dates to date/datetime data type and just put that values in the between.
And receive that dates parameters as date/datetime types if you can.
I believe you are looking for this?
You where missing the WHERE clause and I corrected a typo for your first column selected.
ALTER PROCEDURE [dbo].[select_User_attendance_master_Date]
(
#From_date NVarchar(100),
#To_date NVarchar(100)
)
AS
BEGIN
SELECT
Employee_Attendance_Code,
Employee_Attendance.Attendance_day as Attendanceday
FROM Employee_Attendance
WHERE Employee_Attendance.Attendance_day BETWEEN #From_date AND #To_date
END

SQL Server Include user function result into select query

I have this stored function
function GetPrevReading(
#utility int,
#asofdate datetime
) returns decimal(10,5)
This function returns the previous meter reading from the table with the following fieds:
utility - int
date - datetime
reading - numeric(18,4)
When I use select on this table I want to set a date as a parameter and get this from the table:
Utility Previous Reading
(distinct) GetPrevReading(utility from query, #date from parameter)
I want the function GetPrevReading to take parameter 'utility' from the current row.
Is it possible to accompish this with a query or should I make a stored procedure?
For example, this is the table:
Utility Date Reading
1 2013-10-1 105.6
1 2013-11-1 123.72
2 2013-10-1 226.1
2 2013-10-1 238.18
Now, if I set parameter #date to 2013-10-29 I should get this result:
Utility PreviousReading
1 105.6
2 226.1
Here, my function should get #utility=1 and #asofdate='2013-10-29' on the first row and #utility=2 and #asofdate='2013-10-29' on the second one.
Try this out. I fixed some inconsistencies in your data types, and assumed that your last line of sample data really should have had 2013-11-01 as the date. Also, the way that the function is written, it's not getting the previous reading, but the reading on that date.
CREATE TABLE MyTable (
Utility Int,
Date Date,
Reading Decimal(10,5)
);
INSERT INTO MyTable (Utility, Date, Reading)
VALUES
(1,'2013-10-01', 105.60),
(1,'2013-11-01', 123.72),
(2,'2013-10-01', 226.10),
(2,'2013-11-01', 238.18);
CREATE FUNCTION dbo.GetPrevReading(
#utility int,
#asofdate datetime
)
RETURNS Decimal(10,5)
AS
BEGIN
RETURN (
SELECT TOP 1 Reading
FROM MyTable
WHERE Utility = #Utility
AND Date = #asofdate
ORDER BY Date DESC
)
END;
SELECT
Utility
,Date
,dbo.GetPrevReading(Utility, Date)
FROM (
SELECT Utility, Max(Date) Date
FROM MyTable
WHERE Date < '2013-10-29'
GROUP BY Utility
) x;
Am I understanding the question; the function returns for this call
GetPrevReading( 1,2013-10-29)
Returns
1, 105.6
2, 226.1
And you want to join between the function and its results and the underlying table? You can do this in SQL 2005 + using the Apply join
Select
…
From tblUtilityReadings
Cross Apply GetPrevReading(tblUtilityReadings.utility, #date)

SQL: datetime as a variable [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Trying to using parts of datetime as a variable in a procedure, so a parameter would be a month like 'June'. Here's what I wrote
/* 3. Create a stored procedure called sp_product_listing listing a specified product ordered during a specified month and year. The product and the month and year will be input parameters for the stored procedure. Display the product name, unit price, and quantity in stock from the products table, and the supplier name from the suppliers table. Run the stored procedure displaying a product name containing Jack and the month of the order date is June and the year is 2001. The stored procedure should produce the result set listed below.*/
CREATE PROCEDURE sp_product_listing
(
#product varchar(40),
#month datetime,
#year datetime
)
AS
SELECT
'product_name'=products.name,
'unit_price'=products.unit_price,
'quantity_in_stock'=products.quantity_in_stock,
'supplier_name'=suppliers.name
FROM
products
INNER JOIN suppliers ON suppliers.supplier_id=products.supplier_id
INNER JOIN order_details ON order_details.product_id=products.product_id
INNER JOIN orders ON orders.order_id=order_details.order_id
WHERE
products.name LIKE '%#product%' AND MONTH(orders.order_date) = #month AND YEAR(orders.order_date) = #year;
GO
/*Execute procedure*/
EXECUTE sp_product_listing 'Jack','June','2001'
Procedure is tested working fine until I add the variables, then it goes to H trying to convert varchar to datetime?
I've tried things like #month MONTH(datetime), etc. Not sure how to approach this? Maybe that's not even the problem?
You should not make "#month" datetime because, as its nametype implies, it expects data on the form "date and time" like YYYY/MM/DD hh:mm:ss, and "June" does not fits on the pattern I just presented. If you want just make one column for dates, let's call it [dateofsomething], then, you can pass a parameter "#date" (with type datetime) with a value like a normal date.
Of course, if you want the current date, just use getdate()
Good luck
This should work
CREATE PROCEDURE sp_product_listing
(
#product varchar(40),
#month int,
#year int
)
AS
SELECT
'product_name'=products.name,
'unit_price'=products.unit_price,
'quantity_in_stock'=products.quantity_in_stock,
'supplier_name'=suppliers.name
FROM
products
INNER JOIN suppliers ON suppliers.supplier_id=products.supplier_id
INNER JOIN order_details ON order_details.product_id=products.product_id
INNER JOIN orders ON orders.order_id=order_details.order_id
WHERE
products.name LIKE '%#product%' AND MONTH(orders.order_date) = #month AND YEAR(orders.order_date) = #year;
GO
/*Execute procedure*/
EXECUTE sp_product_listing 'Jack',6,2001
June is not a DateTime value, nor is 2001. Try passing in a complete Date as a single value, then adding a month to determine the search window:
EDIT: Updated sample code.
-- Pass the month and year as a string and an integer.
declare #Month as VarChar(16)
declare #Year as Int
set #Month = 'June'
set #Year = 2001
-- Combine them into a date representing the first day of the desired month and year.
declare #WindowStart as Date = Cast( '1 ' + #Month + Cast( #Year as VarChar(4) ) as Date )
-- Calculate the start of the following month.
declare #WindowEnd as Date = DateAdd( month, 1, #WindowStart )
-- Display the resulting window of dates.
select #WindowStart as WindowStart, #WindowEnd as WindowEnd
Compare using: #WindowStart <= orders.order_date and orders.order_date < #WindowEnd
That will allow the optimizer to use an index on order_date. The importance of this may become apparent later in the term.