Using cast in SQL with multiple column selections - sql

Basically I'd like to get this command to work:
$sql = "SELECT (EntryDate + TotalTime) as DataLine FROM TimeSheet WHERE EmployeeID='AA01'";
EntryDate is in the database as a text, but TotalTime is a Number. I need to cast TotalTime as a text, because I've noticed if I combine two differing types of values, it just blanks out the output.
I know I'm supposed to use CAST(TotalTime as XXX) but I'm not sure what I can legally cast it to (char/nchar doesn't seem to work, neither does string nor text). I always get an error of the form...
Syntax error (missing operator) in query expression '(EntryDate + CAST(TotalTime as string) as DataLine FROM TimeSheet WHERE EmployeeID='AA01''
Could I get some help? Thank you!
EDIT I would like to note this isn't intended to add together the values of EntryDate and TotalTime together to produce a single value. I simply want it to give me the EntryDate value as well as the TotalTime value combined into a single line that would read something like:
"10/31/12 9.25"
EDIT AGAIN I'm sorry for not specifying before, I'm using MSSQL

Try this instead:
SELECT
CAST(EntryDate AS VARCHAR(25)) + CAST(TotalTime AS VARCHAR(10)) as DataLine
FROM TimeSheet
WHERE EmployeeID = 'AA01';
However, if entrydate is a date and the int totaltime is a time, it may be better to consider converting them as a datetime object by adding them as a date part to the time part depending on the RDBMS you are using. And if possible use a DATETIME datatype to represent both date and time parts instead of two parts. Like so:
SELECT DATEADD(hh, totaltime, entrydate)
FROM TimeSheet
WHERE EmployeeID = 'AA01';
SQL Fiddle Demo

MSSQL:
$sql = "SELECT EntryDate+''+CAST(TotalTime as char(25)) as DataLine FROM TimeSheet WHERE EmployeeID='AA01'";
MySQL
$sql = "SELECT CONCAT(EntryDate,' ',CONVERT(TotalTime,char(25))) as DataLine FROM TimeSheet WHERE EmployeeID='AA01'";

Related

finding data lying between a specific date range in sql

I want to find records from my database which lie between any user input date range(say between 10/2/2008 to 26/9/2024). I tried using
SELECT NAME
,TYPE
,COMP_NAME
,BATCH_NO
,SHELF
,MFG_DATE
,EXP_DATE
,QTY
,VAT
,MRP
FROM STOCK_LOCAL
WHERE
convert(VARCHAR(20), EXP_DATE, 103)
BETWEEN convert(VARCHAR(20), #MEDICINEEXP_DATE, 103)
AND convert(VARCHAR(20), #MEDICINEEXPDATE, 103)
but with this query i need to enter perfect date range which is available in my database, it is not giving me data lying in between any date entered.
Thanks in advance
Since it is a poolr designed schema there isnt going to be any decent/Efficient solution for this.
In sql server if you are storing Date or Date & Time data. Use the Data or DATETIME datatypes for your columns.
In your case you are trying to compare a string with passed date. and even when you tried to convert the string (Date) into date datatype you didnt do it correctly.
My suggestion would be Add new columns to your table with Date datatype and update these columns with existing date/string values.
For now you can convert the Date(string) into date datatype using the following code.
DECLARE #MEDICINEEXP_DATE DATE = 'SomeValue1'
DECLARE #MEDICINEEXPDATE DATE = 'SomeValue1'
SELECT query....
FROM TableName
WHERE
CAST(
RIGHT(EXP_DATE, 4)
+SUBSTRING(EXP_DATE,CHARINDEX('/',EXP_DATE)+1,2)
+LEFT(EXP_DATE,2)
AS DATE) >= #MEDICINEEXP_DATE
AND CAST(
RIGHT(EXP_DATE, 4)
+SUBSTRING(EXP_DATE,CHARINDEX('/',EXP_DATE)+1,2)
+LEFT(EXP_DATE,2)
AS DATE) <= #MEDICINEEXPDATE
Note
This solution will get you the expected results but very inefficient method. It will not make use of any indexses on your EXP_DATE Column even if you have a very buffed up index on that column.

Converting m/d/y strings to datetime yields conversion error

Here is the code I'm using:
SELECT SalesItemPK
,FieldName
,Value /*Convert date to the first of the selected month*/
FROM [Oasis].[dbo].[vw_SALES_SalesItemDetails]
WHERE SalesItemPK IN(
1425
,1225
,1556
,1589
,1599
,1588
,1590)
AND FieldName = 'Estimated Ship Date'
AND CONVERT(DATETIME, Value) >= CONVERT(DATETIME, '1/1/2010')
(I'm selecting just those PKs because those are all the rows in the query.)
This is the error I receive:
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value
Below is a sample of the data returned from my view. The final solution actually converts the values to the first of their respective months. But an error is thrown either way.
When I remove the WHERE, it works fine. So there's something strange going on there I can't seem to figure out so far. Any ideas?
Odds are, either the date is being interpreted as d/m/y (and the first row fails because there is no 18th month), or you have a piece of data in there where the first part (month) is > 12.
To find offending rows:
SELECT Value FROM [Oasis].[dbo].[vw_SALES_SalesItemDetails]
WHERE SalesItemPK IN (1425,1225,1556,1589,1599,1588,1590)
AND ISDATE(Value) = 0;
(And if you find offending rows, obviously, fix them.)
You can also make sure the values are interpreted as m/d/y (and won't fail on other garbage in the column) using:
SELECT SalesItemPK, FieldName, Value,
FirstOfMonth = CASE WHEN ISDATE(Value) = 1 THEN
DATEADD(DAY,1-DAY(CONVERT(DATETIME,Value,101)),CONVERT(DATETIME,Value,101)) END
FROM [Oasis].[dbo].[vw_SALES_SalesItemDetails]
WHERE SalesItemPK IN (1425,1225,1556,1589,1599,1588,1590)
AND FieldName = 'Estimated Ship Date'
AND CASE WHEN ISDATE(Value) = 1 THEN CONVERT(DATETIME, Value, 101)
ELSE NULL END >= '20100101';
Also note that just because you perform a WHERE clause on the PK values, does not mean SQL Server has to evaluate that condition first. It could try to convert every row in the view (heck, every row in the source table) to a DATETIME first. Which is why I also added a CASE expression to the SELECT list, just in case. No pun intended. I also offered my suggestion on how to calculate the first of the month easily (a lot of people tend to do really strange things, like convert to string).
Do you have any idea how much simpler this query would be if the view exposed a separate column as datetime, e.g.
, DateValue = CASE WHEN ISDATE(Value) = 1 THEN CONVERT(DATETIME, Value, 101)
Then the query could be:
SELECT SalesItemPK, FieldName, DateValue,
FirstOfMonth = DATEADD(DAY, 1-DAY(DateValue), DateValue)
FROM [Oasis].[dbo].[vw_SALES_SalesItemDetails]
WHERE SalesItemPK IN (1425,1225,1556,1589,1599,1588,1590)
AND DateValue >= '20100101';
In fact the view could also expose the FirstOfMonth calculation for you too.
These are some of the many, many, many reasons why you should never, ever, ever store date/time data as strings. At the very least, change the view to present these strings as a completely language-, dateformat- and region-neutral string (yyyymmdd) instead of mm/dd/yyyy.
Its probably one of your date values is not in correct format. Try the following query to find list of values that cant be converted as date.
select value from [Oasis].[dbo].[vw_SALES_SalesItemDetails] where isdate(value) = 0

SQL: Convert String of MMMDD to Datetime

I have a nvarchar(5) column of data that is formatted MMMDD (for example, OCT26). With my select statement, I'd like to convert it to a datetime data type with the current year, and then save that datetime value as an alias, say, UsefulDate. So something like 10-26-2012.
Something like: SELECT (whatever SQL gets the job done) AS UsefulDate
The exact formatting doesn't matter; I just need to be able to compare two dates together with greater than and less than operators. Also, sometimes the column will be blank. In that case, I'd like to set the alias to blank as well. Is this possible?
Thanks for your help!
You can convert varchar fields in format MMMDD to date with current year with :
select convert(datetime,'OCT26'+','+cast(year(getdate()) as varchar),107)
So your query would be something like :
select convert(datetime,case varcharDate when '' then null else varcharDate end +
','+cast(year(getdate()) as varchar),107) as UsefulDate
from table
select CASE WHEN ISDATE(mmmdd+' '+right(year(getdate()),4)) = 1
THEN CAST(mmmdd+' '+right(year(getdate()),4) as datetime)
END UsefulDate, *
from tbl

SQL Server - Querying DateTime stored as string

I have an existing database that was setup (for whatever reason??) to store a date time as a string. I need to run a query for records that where entered between a specific date range but am not having any luck.
The string field is formatted like 1/25/2007 - 4:39 PM. I have tried the query below but of course it doesn't work. Any help would be appreciated.
SELECT ID, CUSTOMER, ADD1, ADDZ, CITY, STATE, LASTD, ORDNUM
FROM dcar
WHERE (STATE = N'OR') AND (CAST(dcar.LASTD AS datetime) BETWEEN convert(smalldatetime, '10/01/2011', 101) AND convert(smalldatetime, '10/31/2011', 101))
PS - I have no idea why the developer decided to store dates this way!!!!
I think you should be able to cast the field as a datetime, if you remove the dash between the date and time with the REPLACE function like so:
SELECT ID, CUSTOMER, ADD1, ADDZ, CITY, STATE, LASTD, ORDNUM
FROM dcar
WHERE (STATE = N'OR') AND
CAST(REPLACE(dcar.LASTD, ' -', '') AS DATETIME) BETWEEN '10/01/2011' AND '10/31/2011'
It looks like you're not really using the time part of the value stored. If so, this may work for you:
Use the string manipulation functions (http://msdn.microsoft.com/en-us/library/ms181984.aspx) to extract the date part of the string and then use convert() to convert that to a datetime. You could, for example, use CHARINDEX() to find the index of the "-" and then use SUBSTRING() to get the characters up to that point. Then use convert, passing in the appropriate style value as documented at http://msdn.microsoft.com/en-us/library/ms187928.aspx.

Error in Updating a table using datetime as parameter in Stored procedure

Here is my query:
UPDATE Mst_Attendance
SET FNLogged=#FNLogged,
ANLogged=#ANLogged,LogTime=#LogTime,LogOuttime=#LogOuttime
WHERE EmployeeId=#Employee_id AND Atdate = CONVERT(VARCHAR(10), #AtDate, 101) AS [MM/DD/YYYY]
-- Convert(Datetime,#AtDate)
SELECT * FROM Mst_Attendance where Atdate=#AtDate and EmployeeId=#Employee_id
Error occured near AS
Just remove the AS [MM/DD/YY] snippet. You don't need it, and it's not valid inside a WHERE clause.
And what in the world are you doing storing dates as strings in your database? That's just a bad idea. Are you trying to truncate the time portion?
AS in that context is used to give an alias to a column or table; there is no sense in an AS here, since that isn't a select.
You have already specified a format via CONVERT(VARCHAR(10), #AtDate, 101), but this also seems odd; dates are not strings. If you are matching on a datetime - keep everything as a datetime.
If you are actually trying to remove the time portion (leaving just a date), either a: don't send the time (cut it at the caller), or b: do something like:
set #date = cast(floor(cast(#date as float)) as datetime)