Converting String to Int in SQL Server - sql-server

I have column Terms in my table and it contains data like this:
30D, 40D, etc.
D represents days.
My question: how can I sum date in Terms column? How can I convert string to int?
Thank you in advance.

Just use REPLACE to ditch the D and CONVERT to convert the varchar to a number....
SELECT SUM(CONVERT(int, REPLACE(Terms,'D',''))) FROM TableName
Edit: Commentor is right, CAST would work too.
And I dont get all the down votes. The guy's just asking a SQL question.
Jeez... Tough crowd.
Edit2:
OK, based on comments, it seems like you would like to get a "due date" from the terms (say, TODAY + 30D or "today + 30 days"). To do that, we'd need a DATE column. OR, we can just use today's date (GETDATE())
Assume your table has a date column called ... dt
The SQL to pull dt+'30D' would require us to add 30 "days" to dt.
DATEADD will add days, and the aforementioned CONVERT+REPLACE combo will convert '30D' to just plain '30' ...
So, you end up with the following SQL:
SELECT DATEADD(day, CONVERT(int, REPLACE(Terms,'D','')), dt) FROM TableName
The 'day' tells DATEADD to add days (that seems really obvious ... now),
the CONVERT+REPLACE tells it how many days to add
AND - dt is our column name.
SO - how about just adding "30D" to TODAY? Easy. We just swap out dt with GETDATE() ...
SELECT DATEADD(day, CONVERT(int, REPLACE(Terms,'D','')), GETDATE()) FROM TableName

SELECT AVG(SALARY) - AVG(CONVERT(int, REPLACE(SALARY,'0','')))
FROM EMPLOYEES;

Related

Epoch timestamp converted to datetime but how to sort records later on

I got my answer from Martin on how to convert epoch to date time but now I am facing another issue. How to do I filter records that are only entered today or some other date?
I created view with DATEADD(SECOND, Timing, '19700101') and want to filter out records.
select * from [dbo].[vw_records]
where Timing like '%23-10-2019%'
This way I am not able to query datetime based on that view. So as far the conversion it is good solution but for querying records not too good.
On other hand, maybe it is better to convert it in the table and then query results. hm...
Any suggestions please..
If you want rows from today, then use inclusive Date logic:
SELECT {Columns list}
FROM YourTable
WHERE DateColumn >= CONVERT(date, GETDATE())
AND DATECOLUMN < DATEADD(DAY, 1, CONVERT(date, GETDATE()));
For today, this'll return all rows on or after 2019-10-28T00:00:00:00.000 and before (but not including) 2019-10-29T00:00:00:00.000.

How to convert varchar into usable date in SQL Server?

I am having an issue converting an nvarchar into a date.
The column title is DOS and the dates are formatted like 05-03-2012.
I am trying to convert to a date so I can filter in the where clause.
I have seen explanations using CONVERT(datetime, DOS, 101) but I am not sure where this would go? In the select? In the where clause? Is this the best method to convert varchar into date?
SELECT BedSize
,avg(contributionmargin) AS ContributionMargin
FROM Summary
WHERE DOS > '06-30-2016'
GROUP BY bedsize
HAVING avg(contributionmargin) > 10000
ORDER BY contributionmargin DESC
In this example the where clause is just looking at the '06' in the date and selecting values that are greater than 06, so the results include:
07/01/2013
07/02/2009
08/31/2009
09/25/2012
11/03/2016
12/03/2008
The problem is that the years are ignored.
Option 1:
Add a new datetime column (let's suppose DOSDate) in the table and then run this query
update mytable set DOSDate = STR_TO_DATE(DOS,'%m-%d-%Y')
But future inserts in mytable will also needs to be converted and stored in DOSDate` column.
Option 2:
If you cannot add a new column, use this in where clause
select * from mytable where STR_TO_DATE(DOS,'%m-%d-%Y') > p_mydate
Since you have not provided a query, the above is a sample query to illustrate the point.
UPDATE
Initially you marked your question related to MySQL. For SQL Server you may use CAST or CONVERT instead of STR_To_DATE https://msdn.microsoft.com/en-us/library/ms187928(v=sql.90).aspx
I was able to use the convert function for SQL Server.
This code works:
SELECT BedSize
,avg(contributionmargin) AS ContributionMargin
FROM Summary
WHERE Convert(DATE, DOS, 101) > '06-30-2016'
GROUP BY bedsize
HAVING avg(contributionmargin) > 10000
ORDER BY contributionmargin DESC

SQL: Query where date is like today

I have a little problem with my SQL Query:
I have this value on my table: 2014-10-23 00:00:00
I have a record like this each 2 minutes every day, and I need to SELECT all the value of today.
Now I made this:
WHERE mytable.data LIKE CURDATE()
and it doesn't work. I tried a lot of things found here on stackoverflow and nothing could help me.
Thanks for answer.
You don't say which version of SQL Server you are using, if you have the DATE data type available you can cast the datetime returned by getdate() or CURRENT_TIMESTAMP to strip off the time part.
But then you need a range to find all the matching rows, something like:
SELECT *
FROM mytable
WHERE mytable.data >= CAST(GETDATE() AS date)
AND mytable.data < CAST(DATEADD(day, 1, GETDATE()) AS date)
SQL Fiddle

need to change date format in Varchar column

I have DOB varchar column which contains date value. I am getting dates in mm/dd//yyyy format.
I have to change format of all these values to yyyymmdd format in DOB column. I can't use datetime datatype for DOB column as per customer’s demand.
Please suggest what can be done.
UPDATE dbo.tablename
SET DOB = CONVERT(CHAR(8), CONVERT(DATETIME, DOB, 101), 112);
Of course there is no guarantee that all of the data in there right now is valid m/d/y data. Someone could have entered d/m/y, or something that is entirely not a date at all.
You can get close by fixing any rows that come back from this query:
SELECT DOB FROM dbo.tablename WHERE ISDATE(DOB) = 0;
Of course this won't identify any rows where someone entered 09/05/2013 and meant May 9th, not September 5th.
This also won't prevent future strings from being entered that are not valid dates (or not the dates that the user who entered them expected them to represent).
Strongly consider having your customer read these posts. We have date-related data types for a reason.
Bad habits to kick : choosing the wrong data type
Bad habits to kick : mis-handling date / range queries
You should be able to do .....
SELECT CAST( YEAR(DOB_Column) AS VARCHAR(4)) +
CAST( LPAD(MONTH(DOB_Column),2,0) AS VARCHAR(2)) +
CAST( LPAD(DAY(DOB_Column),2,0) AS VARCHAR(2)) AS MyDate
FROM MyTable
My original answer was
SELECT CONVERT(VARCHAR, CONVERT(DATETIME,'12/01/2012'), 112)
but I was typing too slow. So another alternative would be, but this is not a robust solution because it relies on formatting to be the same.
DECLARE #MyDate VARCHAR(12) = '12/25/2012';
SELECT SUBSTRING(#MyDate, 7, 4) + SUBSTRING(#MyDate, 4, 2) + SUBSTRING(#MyDate, 0, 3)

SQL Server Converting int to Date

I have a scenario where I have an int column with the following dates for example:
20131210
20131209
What I want is, I want to convert the above to a date datatype so that I can use it with GETDATE() function.
This is my try but I am getting an error:
SELECT CONVERT(DATETIME, CONVERT(varchar(8), MyColumnName))
FROM MyTable
WHERE DATEADD(day, -2, CONVERT(DATETIME, CONVERT(CHAR(8), MyColumnName))) < GetDate()
This is the error I am getting:
Conversion failed when converting date and/or time from character string.
You have at least one bad date in your column (it could be 99999999 or 20130231 or who knows). This is what happens when you choose the wrong data type. You can identify the bad row(s) using:
SELECT MyColumnName FROM dbo.MyTable
WHERE ISDATE(CONVERT(CHAR(8), MyColumnMame)) = 0;
Then you can fix them or delete them.
Once you do that, you should fix the table. There is absolutely no upside to storing dates as integers, and a whole lot of downsides.
Once you have the date being stored in the correct format, your query is much simpler. And I highly recommend applying functions etc. to the right-hand side of the predicate as opposed to applying it to the column (this kills SQL Server's ability to make efficient use of any index on that column, which you should have if this is a common query pattern).
SELECT MyColumnName
FROM dbo.MyTable
WHERE MyColumnName < DATEADD(DAY, 2, GETDATE());
Try:
CREATE TABLE IntsToDates(
Ints INT
)
INSERT INTO IntsToDates
VALUES (20131210)
, (20131209)
SELECT CAST(CAST(Ints AS VARCHAR(12)) AS DATE)
FROM IntsToDates
I've had a similar problem where I need to convert INT to DATE and needed to cater for values of 0. This case statement did the trick for me
CASE MySourceColumn
WHEN ISDATE(CONVERT(CHAR(8),MySourceColumn)) THEN CAST('19000101' AS DATE)
ELSE CAST(CAST(MySourceColumn AS CHAR) AS DATE)
END
AS MyTargetColumn

Resources