[FIXED] Converting String to Int in SQL Server

Issue

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.


Solution

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
  1. The 'day' tells DATEADD to add days (that seems really obvious ... now),

  2. the CONVERT+REPLACE tells it how many days to add

  3. 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


Answered By - bri
Answer Checked By - Timothy Miller (sql.easybugfix Admin)

Related Posts

Post a Comment