Showing posts with label int. Show all posts
Showing posts with label int. Show all posts

Thursday, March 29, 2012

converting datetime int

I have tables with columns that stores datetime data in int format on
SQL server 2000. For example, the datetime for '4/5/2004
00:00:00.000am' is stored as 1081180800. "4/4/2004 11:59:59.000pm' is
1081180799. I need to generate reports that display datetime columns
in "mm/dd/yyyy hh:mn:ss" format with am or pm at the end. Bellow is
my query statment.

select iorg_name as org, ref_num as [ticketnum], c_first_name as
[firstname], c_last_name as [lastname], sym as type, [description] as
summary, status, dateadd(s,open_date,'12/31/1969 08:00:00pm') as
opened, dateadd(s,last_mod_dt,'12/31/1969 08:00:00pm') as irt,
dateadd(s,close_date,'12/31/1969 08:00:00pm') as closed from
AHD.dbo.HDreports reportview WHERE reportview.open_date >= 1080882000
AND reportview.open_date <= 1081227599.

The result shows correctly with those records that are in daylight
saving time. Those records in standard time show 1 hour behind.

Does anyone know how to make this query correctly display the data in
properly?js (androidsun@.yahoo.com) writes:
> I have tables with columns that stores datetime data in int format on
> SQL server 2000. For example, the datetime for '4/5/2004
> 00:00:00.000am' is stored as 1081180800. "4/4/2004 11:59:59.000pm' is
> 1081180799. I need to generate reports that display datetime columns
> in "mm/dd/yyyy hh:mn:ss" format with am or pm at the end. Bellow is
> my query statment.
>...
> The result shows correctly with those records that are in daylight
> saving time. Those records in standard time show 1 hour behind.
> Does anyone know how to make this query correctly display the data in
> properly?

That was a very odd way of storing dates, and probably not the best one.
Apparently this is some variation of Unix, where time is counted as number
of seconds since 1970-01-01 00:00:00, except that here the staring point
is 1969-12-30 20:00:00.

SQL Server is not timezone aware, so you should not expect to be able
to get fully accurate results. You are probably best of getting the
integer value to the client, and try the Windows functions for date
and time. They are likely to work out better.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

converting Datatypes:

Hi All,

how do you convert from a date to an int ? as well as converting from Varchar to and Int

in SQL server 2000 ?

I am retrieving the GetDate() which i store in column as Varchar, i then want to use it within my select statement to calulate data which i want to return i.e

DECLARE @.DateValue AS VARCHAR(20)

SELECT @.DateValue = ApplicationSettingValue FROM ApplicationSettings WHERE ApplicationSettingKey = 'ProcessDate'

print convert(int,@.DateValue) - 5
print GetDate() - 35


SELECT ccy_code, NULL, xrate_date, sterling_xrate
FROM SylvanTrans.dbo.SIADHP_XRate_Hist
WHERE xrate_date >= (CONVERT(int, @.DateValue) - 35 )
ORDER BY xrate_date

now my as you can see in my WHERE CLAUSE i want to calculate what is returned using the GETDATE() stored in my @.DateValue Variable, but the conversion throws a syntax error:

Server: Msg 245, Level 16, State 1, Line 3
Syntax error converting the varchar value 'GetDate()' to a column of data type int.

what am idoing wrong? i know it is something simple, unless there is no conversion from varchar to int?, i also tried setting the datatype for my variable as datetime but i got the same sort of error with DATETIME replacing the VARCHAR in the error!!!

thanks

regards

Hi,

why don′t use use the associated function for dealing with datetime like DATEADD ? You can also add negative dateparts to a datetime like
DATEADD(dd,-35,SomeDate)

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de
|||

thanks for your reply,

yes i did see that function, but i neet to have a seperate table which stores the GetDate() so that in my sotred procs

i can do a select on its location and do things like :

select * from tablename

where @.valueDate - 1 > 5

where @.valueDate has the getDate () from my Applicationsettings Table, if i use the DateAdd() i wont be able to do this you see...

|||I think I did not got your point. COuld you explain this in more detail ?

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de

Tuesday, March 27, 2012

Converting data question

I need to combine two columns and copy them to another. One column is varchar and one is decimal (3,0) and the destination column is int. The column of decimal contains only 1 and 2 digit numbers. I need to perface a 0 to the data with 1 digit before combining the two columns. If someone could guide me here, I'd appreciate it. I've been trying to use cast and convert with no success.Your destination column should be a varchar column if the column from your source varchar is not an integer. You can post a set of sample data and expected result here to help answer your question.|||Source Columns Destination
Varchar Dec int
0660 10 66010
0660 2 66002
0660 3 66003
0660 11 66011|||

Kinny:

I put together a quick mock-up of what I think you are trying to do. Do either of the output columns look like what you are trying to do?

Dave

-- --
-- This mock-up works correctly for "correct values" as discribed in the request.
-- However, it does not know what to do with most "error conditions." If you don't
-- have to worry about "incorrect values" this select should work fine
--
-- Problem areas:
--
-- 1. What do you do with nulls?
-- 2. What do you do with 3-digit numbers?
-- 3. What do you do with negative numbers?
-- --
set nocount on
declare @.mockUp table
( sampleString varchar (20) not null,
sampleDecimal decimal (3,0) null
)

insert into @.mockUp values ('testView', null) -- ? Do you have to worry about null?
-- ? If so, display double-zero for nulls?
insert into @.mockUp values ('testView', 0) -- O0; OK
insert into @.mockUp values ('testView', 4) -- 04; OK
insert into @.mockUp values ('testView', 21) -- 21; OK
insert into @.mockUp values ('nextSample', 99) -- 99; OK
insert into @.mockUp values ('negative', -1) -- -1; Not sure; is this a problem?
insert into @.mockUp values ('negative', -99) -- 99; Wrong; is this a problem?
insert into @.mockUp values ('tooBig', 100) -- 00; Wrong; is this a problem?
--select * from @.mockUp

select sampleString,
sampleDecimal,
sampleString + isnull ( right('0'+convert(varchar(3), sampleDecimal), 2), '00')
as [String First],
isnull ( right('0'+convert(varchar(3), sampleDecimal), 2), '00') + sampleString
as [Decimal First]
from @.mockUp


-- --
-- Sample Output:
-- --

-- sampleString sampleDecimal String First Decimal First
-- -- - - -
-- testView NULL testView00 00testView
-- testView 0 testView00 00testView
-- testView 4 testView04 04testView
-- testView 21 testView21 21testView
-- nextSample 99 nextSample99 99nextSample
-- negative -1 negative-1 -1negative
-- negative -99 negative99 99negative
-- tooBig 100 tooBig00 00tooBig

|||

Hi,

Here is the update statement for question:

UPDATE yourTable

SET DesINTColumn= CAST(CAST(CONVERT(int, VarCharColumn1) AS varchar)+ RIGHT('0' + CAST(DecimalColumn1 AS varchar), 2) AS INT)

Sunday, March 25, 2012

Converting Binary Image to Readable Text

I have a table that contains the following two columns:

BITS (image(16))
BIT_LENGTH (int(4))

When I look at the table, I see "OLE Object" in the BITS column. What
syntax should I use in a SELECT statement to convert the binary image
info contained in "BITS" into simple text that I can read? What role
does the BIT_LENGTH field play?An image column can store any binary data, so you need to know what the
data represents before you can display it - it could be a Word
document, a PDF, an MP3 etc. Do you already know exactly what the
column is storing ('text' is the normal data type for large amounts of
text data)? As for BIT_LENGTH, it could mean anything, depending on the
data model - there's no need for an image column to have an associated
length column with it.

It sounds a little like you've just taken over a database from someone
else? If so, you might want to review this chapter from the SQL2000
Resource Kit, which provides more detailed information about storing
and retrieving BLOBs:

http://www.microsoft.com/technet/pr...art3/c1161.mspx

Simon

Converting a varchar to int

I am struggling with converting a certain varchar column into an int.
I have a table that has 2 fields - one field holds the loan number and
the other field holds the codes associated with that loan number.
Here's some example data:

Loan# Codes
11111 24-13-1
22222 1
33333 2-9

I need to check the Codes field for certain code numbers. The Select
statement I'd like to use is:

SELECT Loan#
FROM Table1 WHERE Codes IN (2, 13, 1)
/*My desired results is that all loans from the above example would be
selected because they all have one of these codes*/

Of course I cannot use the above statement because the Codes field is a
varchar. And if I put single quotes around the numbers in my IN
statement I don't get the desired results; the fields with multiple
codes are excluded.

But how do I convert this varchar to an int? A simple convert or cast
statement doesn't work. I've looked all over the web to find how to do
this, but have not been able to figure it out. Any help would be much
appreciated.Patti wrote:

Quote:

Originally Posted by

I am struggling with converting a certain varchar column into an int.
I have a table that has 2 fields - one field holds the loan number and
the other field holds the codes associated with that loan number.
Here's some example data:
>
Loan# Codes
11111 24-13-1
22222 1
33333 2-9


A classic violation of first normal form:

http://en.wikipedia.org/wiki/First_..._ single_field
If at all possible, change your table to look like this:

Loan# Code
11111 24
11111 13
11111 1
22222 1
33333 2
33333 9

Quote:

Originally Posted by

I need to check the Codes field for certain code numbers. The Select
statement I'd like to use is:
>
SELECT Loan#
FROM Table1 WHERE Codes IN (2, 13, 1)
/*My desired results is that all loans from the above example would be
selected because they all have one of these codes*/


and then this simply becomes

SELECT Loan#
FROM Table1
WHERE Code in (2, 13, 1)

That said, if fixing the 1NF violation will take a while, then in the
short term, you can do something like the following. (You can't convert
Codes to int, because e.g. '24-13-1' isn't a number. Instead, you must
convert the search terms from int to varchar.)

SELECT Loan#
FROM Table1
WHERE '-'+Codes+'-' like '-2-'
OR '-'+Codes+'-' like '-13-'
OR '-'+Codes+'-' like '-1-'

Also, you may need SELECT DISTINCT, in case some Loan#s have multiple
matches and you only want to include them once.|||I can't change the actual table, but I can create a stored proc that
inserts it correctly into another table. I didn't even think to do
that (**duh**)! Thank you very much for your assistance!

Ed Murphy wrote:

Quote:

Originally Posted by

Patti wrote:
>

Quote:

Originally Posted by

I am struggling with converting a certain varchar column into an int.
I have a table that has 2 fields - one field holds the loan number and
the other field holds the codes associated with that loan number.
Here's some example data:

Loan# Codes
11111 24-13-1
22222 1
33333 2-9


>
A classic violation of first normal form:
>
http://en.wikipedia.org/wiki/First_..._ single_field
>
If at all possible, change your table to look like this:
>
Loan# Code
11111 24
11111 13
11111 1
22222 1
33333 2
33333 9
>

Quote:

Originally Posted by

I need to check the Codes field for certain code numbers. The Select
statement I'd like to use is:

SELECT Loan#
FROM Table1 WHERE Codes IN (2, 13, 1)
/*My desired results is that all loans from the above example would be
selected because they all have one of these codes*/


>
and then this simply becomes
>
SELECT Loan#
FROM Table1
WHERE Code in (2, 13, 1)
>
That said, if fixing the 1NF violation will take a while, then in the
short term, you can do something like the following. (You can't convert
Codes to int, because e.g. '24-13-1' isn't a number. Instead, you must
convert the search terms from int to varchar.)
>
SELECT Loan#
FROM Table1
WHERE '-'+Codes+'-' like '-2-'
OR '-'+Codes+'-' like '-13-'
OR '-'+Codes+'-' like '-1-'
>
Also, you may need SELECT DISTINCT, in case some Loan#s have multiple
matches and you only want to include them once.

|||Ed Murphy (emurphy42@.socal.rr.com) writes:

Quote:

Originally Posted by

SELECT Loan#
FROM Table1
WHERE '-'+Codes+'-' like '-2-'
OR '-'+Codes+'-' like '-13-'
OR '-'+Codes+'-' like '-1-'


Seems like some % are missing.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||This might work:
SELECT Loan#
FROM Table1
WHERE patindex('%[2,13,1]%',Codes) 0

Patti wrote:

Quote:

Originally Posted by

I am struggling with converting a certain varchar column into an int.
I have a table that has 2 fields - one field holds the loan number and
the other field holds the codes associated with that loan number.
Here's some example data:
>
Loan# Codes
11111 24-13-1
22222 1
33333 2-9
>
I need to check the Codes field for certain code numbers. The Select
statement I'd like to use is:
>
SELECT Loan#
FROM Table1 WHERE Codes IN (2, 13, 1)
/*My desired results is that all loans from the above example would be
selected because they all have one of these codes*/
>
Of course I cannot use the above statement because the Codes field is a
varchar. And if I put single quotes around the numbers in my IN
statement I don't get the desired results; the fields with multiple
codes are excluded.
>
But how do I convert this varchar to an int? A simple convert or cast
statement doesn't work. I've looked all over the web to find how to do
this, but have not been able to figure it out. Any help would be much
appreciated.

|||Erland Sommarskog wrote:

Quote:

Originally Posted by

Ed Murphy (emurphy42@.socal.rr.com) writes:


Quote:

Originally Posted by

Quote:

Originally Posted by

>SELECT Loan#
>FROM Table1
>WHERE '-'+Codes+'-' like '-2-'
> OR '-'+Codes+'-' like '-13-'
> OR '-'+Codes+'-' like '-1-'


>
Seems like some % are missing.


Yes, of course you're right, should be

WHERE '-'+Codes+'-' like '%-2-%'
OR '-'+Codes+'-' like '%-13-%'
OR '-'+Codes+'-' like '%-1-%'

but the approach of "use a stored procedure to copy the data to a
better-normalized table" is probably better. (Oh, and that new
table should probably have an index on the Code column.)

Thursday, March 22, 2012

Converting a field from int to varchar during query

I have a query where I am writing the following statement:
select * from .....
where table1.field1 = table2.field2
....
....
....
field2 is a varchar field and field1 is an int field. Field2 contains the
data mapping data for field1 and also other unrelated data as character
strings.
How do I run this query without getting the error - "Syntax error converting
the varchar value 'XXXX' to a column of data type int."
Thanks,
Jignesh.
On Wed, 2 Feb 2005 13:07:04 -0800, Jig Bhakta wrote:

>I have a query where I am writing the following statement:
>select * from .....
>where table1.field1 = table2.field2
>...
>...
>...
>field2 is a varchar field and field1 is an int field. Field2 contains the
>data mapping data for field1 and also other unrelated data as character
>strings.
>How do I run this query without getting the error - "Syntax error converting
>the varchar value 'XXXX' to a column of data type int."
Hi Jignesh,
Try:
select * from .....
where CAST(table1.field1 AS varchar(10)) = table2.field2
....
....
....
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)
|||Nope, still getting the error.
"Hugo Kornelis" wrote:

> On Wed, 2 Feb 2005 13:07:04 -0800, Jig Bhakta wrote:
>
> Hi Jignesh,
> Try:
> select * from .....
> where CAST(table1.field1 AS varchar(10)) = table2.field2
> ....
> ....
> ....
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)
>
|||On Thu, 3 Feb 2005 13:01:08 -0800, Jig Bhakta wrote:

>Nope, still getting the error.
Hi Jignesh,
In that case, you better post the complete query. Best is to include
CREATE TABLE statements and INSERT statements with some sample data to
reproduce the error.
Here's a small script that shows that my change does work on my system, so
your error is either caused by something else in your query, by something
strange in your data or by a SQL Server bug. If you post a script that
will reproduce the error, we can find which of these three is the cause.
-- Start of repro script that show the error is corrected
create table table1 (field1 int not null)
create table table2 (field2 varchar(20) not null)
go
insert table1 (field1) select 1 union all select 2
insert table2 (field2) select '1' union all select 'XXXX'
go
print 'Original'
print ''
select * from table1, table2
where table1.field1 = table2.field2
print '--'
go
print ''
print 'Corrected'
print ''
select * from table1, table2
where CAST(table1.field1 AS varchar(10)) = table2.field2
print '--'
go
drop table table1
drop table table2
go
-- Output:
Original
field1 field2
-- --
1 1
Server: Msg 245, Level 16, State 1, Line 3
Syntax error converting the varchar value 'XXXX' to a column of data type
int.
Corrected
field1 field2
-- --
1 1
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)
|||Jig,
Try this:
select * from ...
where
case when table1.field1 not like '%[^0-9]%' then cast(table1.field1 as
int) end
= table2.field2
The reason for the error is that a varchar = integer comparison
causes the varchar to be converted to an integer, so XXXX is
getting converted to an integer for the comparison. The CASE
statement causes the query to compare the column field1 with
field2 only if field1 is all digits. Otherwise, it compares NULL, which
won't cause an error.
The best thing to do would be not to store numerical and character
data in the same column! If it makes sense to compare two columns,
but they are not the same type, it's usually a sign that the database design
can be improved.
Steve Kass
Drew University
Jig Bhakta wrote:

>I have a query where I am writing the following statement:
>select * from .....
>where table1.field1 = table2.field2
>...
>...
>...
>field2 is a varchar field and field1 is an int field. Field2 contains the
>data mapping data for field1 and also other unrelated data as character
>strings.
>How do I run this query without getting the error - "Syntax error converting
>the varchar value 'XXXX' to a column of data type int."
>Thanks,
>Jignesh.
>

converting a column from varchar to int

I need to copy the data from varchar column into an integer column,
obviously only copying integer values. How can I do this? I am not even
sure how to select data from a column so that the results are only the
numeric ones. Thanks for your help.Et,
ALTER TABLE should allow you to change the datatype of the table assuming
all values are integers.
You could run something like this:
UPDATE tablename
SET col2 = CAST(col1 AS int) --would require the values to be integers not
characters
Check out the ISNUMERIC function for differentiating between integers and
characters. Also see:
http://www.aspfaq.com/show.asp?id=2390
HTH
Jerry
"et" <eagletender2001@.yahoo.com> wrote in message
news:%23nc3kkdxFHA.1252@.TK2MSFTNGP09.phx.gbl...
>I need to copy the data from varchar column into an integer column,
>obviously only copying integer values. How can I do this? I am not even
>sure how to select data from a column so that the results are only the
>numeric ones. Thanks for your help.
>|||Yes, the isnumeric function worked, the cast of course gave me an error
because not all values are integers. This is what I did:
update tbl set newcol=originalcol
where isnumeric(originalcol)=1
Now I have to populate the remaining fields with an integer, any idea an
easy way to do that? I'd like to do it starting with the next available
number, but it doesn't really matter what the number ends up being. This
column will eventually be an identity column.
Thanks!
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:eMYJevdxFHA.2232@.TK2MSFTNGP11.phx.gbl...
> Et,
> ALTER TABLE should allow you to change the datatype of the table assuming
> all values are integers.
> You could run something like this:
> UPDATE tablename
> SET col2 = CAST(col1 AS int) --would require the values to be integers
> not characters
> Check out the ISNUMERIC function for differentiating between integers and
> characters. Also see:
> http://www.aspfaq.com/show.asp?id=2390
> HTH
> Jerry
>
> "et" <eagletender2001@.yahoo.com> wrote in message
> news:%23nc3kkdxFHA.1252@.TK2MSFTNGP09.phx.gbl...
>|||ok...clarify please...IDENTITY is system generated so you don't populate it
with any values. "any number"?
"et" <eagletender2001@.yahoo.com> wrote in message
news:O3CsMRhxFHA.464@.TK2MSFTNGP15.phx.gbl...
> Yes, the isnumeric function worked, the cast of course gave me an error
> because not all values are integers. This is what I did:
> update tbl set newcol=originalcol
> where isnumeric(originalcol)=1
> Now I have to populate the remaining fields with an integer, any idea an
> easy way to do that? I'd like to do it starting with the next available
> number, but it doesn't really matter what the number ends up being. This
> column will eventually be an identity column.
> Thanks!
> "Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
> news:eMYJevdxFHA.2232@.TK2MSFTNGP11.phx.gbl...
>|||That's correct. In other words if this database had been done correctly in
the first place, it would have been an identity column. So now I need to
create this identity column based on numbers that already exist, plus
populate those records with new numbers for those records that don't use an
integer value. Once this is done, then I can make the column an identity
column so that future new records are automatically numbered correctly.
Does that make sense?
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:eBZ%23xThxFHA.1412@.TK2MSFTNGP09.phx.gbl...
> ok...clarify please...IDENTITY is system generated so you don't populate
> it with any values. "any number"?
> "et" <eagletender2001@.yahoo.com> wrote in message
> news:O3CsMRhxFHA.464@.TK2MSFTNGP15.phx.gbl...
>|||You cannot alter an existing column to be an identity column. You'll have to
create a new table with the identity column and then copy the rows from the
old table into the new one using SET IDENTITY_INSERT ON.
Why are you doing this? Are you planning on using the identity column as the
primary key? Analyze your data more thoroughly - there may be a better
primary key candidate.
To clean up those values try this:
http://milambda.blogspot.com/2005/0...to-integer.html
ML|||No, my primary key is a guid. This column used to be the primary key in an
access database, and was also used for other reasons. Now it's being merged
with the company's sql database. I'm only using the identity feature so it
will automatically provide a number each time a new record is created, which
of course I can do within the program it's being used with also.
"ML" <ML@.discussions.microsoft.com> wrote in message
news:53200E31-72FB-4C15-AF6B-CF6858E3296E@.microsoft.com...
> You cannot alter an existing column to be an identity column. You'll have
> to
> create a new table with the identity column and then copy the rows from
> the
> old table into the new one using SET IDENTITY_INSERT ON.
> Why are you doing this? Are you planning on using the identity column as
> the
> primary key? Analyze your data more thoroughly - there may be a better
> primary key candidate.
> To clean up those values try this:
> http://milambda.blogspot.com/2005/0...to-integer.html
>
> ML|||If the values still need to be unique, then I'd suggest letting the server
assign them.
ML

Converting 7 (int) to 07 (varchar)

Hi,

I'm converting a query from Access to SQL Server.

In this query I select from a column that contains numbers, the result I want is a varchar that is always 2 chars wide..

Ie:
7 should be selected as '07'
12 should be selected as '12'

In the Access-query it's rather nicely done with:
Format(Str(mycolumn),"00")

I could not find a way to make CONVERT do the same job... but I found that:
LEFT('00',2-LEN(CAST(mycolumn as varchar)))+CAST(mycolumn as varchar)
will do the job.

But it feels like it could be done nicer.. any suggestions?Im Pretty new to this myself but how about

RIGHT('00' + CAST(MyColumn as Varchar(2)),2)

Dave|||Thanks, I was too left oriented in my thinking :-)

Tuesday, March 20, 2012

Convert when multiplying smallints

Hi I have two columns of type small int that cause overflow when
multiplied.
SELECT Convert(Bigint,Quantity*UnitCost) FROM Transactions
SELECT Convert(varchar(12),Quantity*UnitCost) FROM Transactions
Arithmetic overflow error converting expression to data type smallint.
What is the correct way to select this?
ThanksTry,
SELECT cast(Quantity as bigint) * UnitCost FROM Transactions
AMB
"hals_left" wrote:

> Hi I have two columns of type small int that cause overflow when
> multiplied.
> SELECT Convert(Bigint,Quantity*UnitCost) FROM Transactions
> SELECT Convert(varchar(12),Quantity*UnitCost) FROM Transactions
> Arithmetic overflow error converting expression to data type smallint.
> What is the correct way to select this?
> Thanks
>|||Which of those statements produce the error? And do you know what values are
producing the error? Small int can go upto 32,767
--
HTH,
Vyas, MVP (SQL Server)
SQL Server Articles and Code Samples @. http://vyaskn.tripod.com/
"hals_left" <cc900630@.ntu.ac.uk> wrote in message
news:1123850544.468656.282800@.g14g2000cwa.googlegroups.com...
Hi I have two columns of type small int that cause overflow when
multiplied.
SELECT Convert(Bigint,Quantity*UnitCost) FROM Transactions
SELECT Convert(varchar(12),Quantity*UnitCost) FROM Transactions
Arithmetic overflow error converting expression to data type smallint.
What is the correct way to select this?
Thanks|||SELECT Cast(Quantity as Bigint)*Cast(UnitCost as Bigint) FROM Transactions
works...but best option?
Lee-Z
"hals_left" <cc900630@.ntu.ac.uk> wrote in message
news:1123850544.468656.282800@.g14g2000cwa.googlegroups.com...
> Hi I have two columns of type small int that cause overflow when
> multiplied.
> SELECT Convert(Bigint,Quantity*UnitCost) FROM Transactions
> SELECT Convert(varchar(12),Quantity*UnitCost) FROM Transactions
> Arithmetic overflow error converting expression to data type smallint.
> What is the correct way to select this?
> Thanks
>

Convert varchar to money/int

I have a table with varchar fields & I need to covert the fields to money
fields. My problem is if the varchar data is of format (581.63) how can I
change that to -581.63 before then doing the convert ie using CAST(July AS
money). Using there CAST function fails because of the brackets.You might try using a CASE expression:
CASE WHEN LEFT(July, 1) = '(' AND RIGHT(July, 1) = ')'
THEN CAST(SUBSTRING(July, 2, LEN(July) - 2) AS money) * -1
ELSE CAST(July AS money) END AS July
Hope this helps.
Dan Guzman
SQL Server MVP
"ChrisB" <ChrisB@.discussions.microsoft.com> wrote in message
news:389EEB22-E89F-413B-823B-5F045C9F3B04@.microsoft.com...
>I have a table with varchar fields & I need to covert the fields to money
> fields. My problem is if the varchar data is of format (581.63) how can I
> change that to -581.63 before then doing the convert ie using CAST(July AS
> money). Using there CAST function fails because of the brackets.

Monday, March 19, 2012

Convert Varchar into Int

Hi

I have imported some varchar figures.

such as 0.050 (we'll call this Field)

I need to convert them into int to be used for calculations.

when I do

CAST(Field as int)

I get...

Server: Msg 245, Level 16, State 1, Line 1
Syntax error converting the varchar value '0.050' to a column of data type int.

Normally I dont get this error?

Anyone?

Quote:

Originally Posted by flickimp

Hi

I have imported some varchar figures.

such as 0.050 (we'll call this Field)

I need to convert them into int to be used for calculations.

when I do

CAST(Field as int)

I get...

Server: Msg 245, Level 16, State 1, Line 1
Syntax error converting the varchar value '0.050' to a column of data type int.

Normally I dont get this error?

Anyone?



INT datatype (SQL Server Books online (BOL)

Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647).

therefore... cast(field as decimal(18,3))
or
cast(field as numeric(18,3))

will return

.050

INT will round to the nearest whole number.

If calculating with decimalised data, numeric data precison and scale will demand decimal or numeric datatype

cast in itself cannot explicitly cast a 0.050 'varchar' value to a whole number
therefore inserting any 0.050 value in an integer would round it down to zero (the nearest whole number)


Regards

Jim :)

Sunday, March 11, 2012

Convert Text to Int

I am trying to write a query in access that will pull results that are
in the database in a text field and convert to where I can get a
average including decimals. Any Ideas?

--------Start SQL------------
SELECT AVG(CAST(dbo_sur_response_answer.answer_text AS int)) AS
avg_correct
FROM (dbo_sur_response_answer
INNER JOIN dbo_sur_subitem
ON dbo_sur_response_answer.subitem_id = dbo_sur_subitem.subitem_id)
INNER JOIN dbo_sur_response
ON dbo_sur_response_answer.response_id = dbo_sur_response.response_id
WHERE (((dbo_sur_response.completed_yn)="Y") AND
((dbo_sur_subitem.subitem_id)=478));
--------End SQL------------Integers do not have decimal places.

CInt() will convert a number held in a string to an Integer type.
CDouble() will convert a number held in a string to a Double type.
Doubles have decimal places.|||On 11 Jan 2006 13:14:43 -0800, 2redline@.gmail.com wrote:

>I am trying to write a query in access that will pull results that are
>in the database in a text field and convert to where I can get a
>average including decimals. Any Ideas?
>
>--------Start SQL------------
>SELECT AVG(CAST(dbo_sur_response_answer.answer_text AS int)) AS
>avg_correct
>FROM (dbo_sur_response_answer
>INNER JOIN dbo_sur_subitem
>ON dbo_sur_response_answer.subitem_id = dbo_sur_subitem.subitem_id)
>INNER JOIN dbo_sur_response
>ON dbo_sur_response_answer.response_id = dbo_sur_response.response_id
>WHERE (((dbo_sur_response.completed_yn)="Y") AND
>((dbo_sur_subitem.subitem_id)=478));
>--------End SQL------------

Hi 2redline,

I doon't know much about Access, but the following should work in SQL
Server. (I assume that using SQL Server is an option, since you
crossposted this to a SQL Server group).

SELECT AVG(CAST(ra.answer_text AS decimal(5,2))) AS avg_correct
FROM dbo.sur_response_answer AS ra
INNER JOIN dbo.sur_subitem AS si
ON si.subitem_id = ra.subitem_id
INNER JOIN dbo.sur_response AS r
ON r.response_id = ra.response_id
WHERE r.completed_yn = 'Y'
AND sit.subitem_id = 478;

I introduced aliasses and changed spacing to make the query more
readable, changed the Access double quotes to standard SQL single quotes
and removed all the unneeded parenthese. The only actual change I made
was CASTing to decimal(5,2) instead of CASTint to int. The average of a
bunch of integers will be integer as well; if you want a result with
decimals, you'll have to use a datatype with decimals (such as
decimal(5,2), which specifies 3 digits to the left and 2 to the right of
the decimal point).

--
Hugo Kornelis, SQL Server MVP|||Had one correction to the last line and removed the t from sit to be
si.

Query Analyzer gives an error of
"Server: Msg 529, Level 16, State 2, Line 1
Explicit conversion from data type text to decimal is not allowed."

This is the same error I got during previous attempts also.

It makes me believe it is something to do with the field type. It is
Text, 16, allow nulls

The following working sql will give me each response but no average
........
SELECT dbo_sur_response_answer.answer_text
FROM (dbo_sur_response_answer INNER JOIN dbo_sur_subitem ON
dbo_sur_response_answer.subitem_id = dbo_sur_subitem.subitem_id) INNER
JOIN dbo_sur_response ON dbo_sur_response_answer.response_id =
dbo_sur_response.response_id
WHERE (((dbo_sur_response.completed_yn)="Y") AND
((dbo_sur_subitem.subitem_id)=[enter SubID]));

Results
------
25.1
20.9
1.12

Any more ideas?
Thanks|||2redline wrote:
Explicit conversion from data type text to decimal is not allowed."

BOL gives the follwing defintion for text:

Variable-length non-Unicode data in the code page of the server and
with a maximum length of 231-1 (2,147,483,647) characters. When the
server code page uses double-byte characters, the storage is still
2,147,483,647 bytes. Depending on the character string, the storage
size may be less than 2,147,483,647 bytes.

I think of this as analogous in some ways to the JET Memo type.

I am guessing that:

the error message is incorrect and that actually this field is of type
varchar or similar,

or

the creator of this table made some careless error in using a text
field to hold string data that might be converted to numeric data type.

Should my guesses be right, a solution is to change the datatype of the
field (carefully!) or ... I suppose that some legerdemain might be
attempted in the T-SQL to convert the Text to VarChar to Money or
whataver .|||On 12 Jan 2006 05:31:14 -0800, 2redline wrote:

>Had one correction to the last line and removed the t from sit to be
>si.
>Query Analyzer gives an error of
>"Server: Msg 529, Level 16, State 2, Line 1
>Explicit conversion from data type text to decimal is not allowed."
>This is the same error I got during previous attempts also.
>It makes me believe it is something to do with the field type. It is
>Text, 16, allow nulls

Hi 2redline,

Lyle's answer gives you the reason for the error.

You can get around this by first casting from text to varchar, then
casting that to decimal:

SELECT AVG(CAST(CAST(ra.answer_text AS varchar(40)) AS
decimal(5,2))) AS avg_correct
FROM dbo.sur_response_answer AS ra
INNER JOIN dbo.sur_subitem AS si
ON si.subitem_id = ra.subitem_id
INNER JOIN dbo.sur_response AS r
ON r.response_id = ra.response_id
WHERE r.completed_yn = 'Y'
AND sit.subitem_id = 478;

(untested - see www.aspfaq.com/5006 if you prefer a tested reply)

--
Hugo Kornelis, SQL Server MVP

Thursday, March 8, 2012

Convert string to hex to int

My table has some hexadecimal data but stored as string. I want to
convert this to hex and then to int. How do I do this?
Data in my table:
139D5
6374
63B2
620B
ABC7
6391
6FA6
604A
139D6
This should be ideally
0x139D5
0x6374
0x63B2
0x620B
0xABC7
0x6391
0x6FA6
0x604A
0x139D6
How do I convert 139D5 to 0x139D5 so that I can cast it as an integer?
declare @.a varchar (1000)
set @.a='139D5'
select cast(cast (@.a as varbinary) as int)
select cast (0x 139D5 as int)
These two stmts give different results. Only the second one is correct.
Please help.
*** Sent via Developersdex http://www.examnotes.net ***
Don't just participate in USENET...get rewarded for it!Why did you save hexadecimal value to string? Instead you can directly
store it as integer
Madhivanan|||Hi
Check out this previous post:
http://tinyurl.com/6syea
John
"male hit" wrote:

> My table has some hexadecimal data but stored as string. I want to
> convert this to hex and then to int. How do I do this?
> Data in my table:
> 139D5
> 6374
> 63B2
> 620B
> ABC7
> 6391
> 6FA6
> 604A
> 139D6
> This should be ideally
> 0x139D5
> 0x6374
> 0x63B2
> 0x620B
> 0xABC7
> 0x6391
> 0x6FA6
> 0x604A
> 0x139D6
> How do I convert 139D5 to 0x139D5 so that I can cast it as an integer?
> declare @.a varchar (1000)
> set @.a='139D5'
> select cast(cast (@.a as varbinary) as int)
> select cast (0x 139D5 as int)
> These two stmts give different results. Only the second one is correct.
> Please help.
> *** Sent via Developersdex http://www.examnotes.net ***
> Don't just participate in USENET...get rewarded for it!
>

convert stored procedures returned output to varchar from int?

I have 1 files, one is .sql and another is stored procedure. SQL file will call the stored procedure by passing the variables setup in the SQL file. However, everything ran well except at the end, I try to get the return value from SP to my SQL file ... which will send notification email. But, I get the following msg ... I am not sure how to fix this ... help!!! :(

Syntax error converting the varchar value 'ABC' to a column of data type int.

SQL file

======================

DECLARE @.S AS VARCHAR(1000)

EXEC @.S = PDT.DBO.SP_RPT
'ABC'

SELECT CONTENT = @.S -- this is the value I am trying to pass as content of the email

EXEC PRODUCTION.DBO.SENDEMAIL'xxx@.hotmail.com', 'Notification', @.S

======================

Stored Procedure

======================

CREATE procedure sp_RPT
( @.array varchar(1000) )
AS

DECLARE @.content AS VARCHAR(2000)

SET @.content = 'RPT: ' + @.array + ' loaded successfully '

SET @.array = 'ABC'
RETURN CONVERT(VARCHAR(1000),@.array)


GO

try

cast( @.array as varchar(1000))

Hope this help

|||Don't use RETURN values in that manner. Either use an output parameter, or a resultset. RETURN values should be used as a control channel, not as a data channel; RETURN's purpose is to terminate control of a stored procedure immediately and also to report on how control was terminated (0 = normal/good, anything else is abnormal/bad).

Saturday, February 25, 2012

convert nvarchar to int

i have got a table

id name pagenumber(nvarchar)

1 gas pg:231-123

2 dff pg:323-123

i need to copy data from this table to another with page number as

id name pagenumber(int)

1 gas 231

2 dff 323

help me

here it is,

Create Table #data (

[id] Varchar(100) ,

[name] Varchar(100) ,

[pagenumber] Varchar(100)

);

Insert Into #data Values( '1','gas','pg:231-123');

Insert Into #data Values( '2','dff','pg:323-123');

select id,name,substring(pagenumber,charindex(':',pagenumber) +1, charindex('-',pagenumber)-charindex(':',pagenumber)-1)

From

#data

|||

Question to 'nasrene',

Are ALL PageNumber values in the form of 'pg:n%-n%'

No space after the colon, alway a dash separating two sets of characters, no other variations?|||

yes all values n form pg.n%-n%

eg:

pg.23-123.

pg.1-23.

pg. 2-34.

for some there are spacesafter pg.

|||

gets error

Invalid length parameter passed to the substring function.
values eg:

pg.23-123.

pg.2-123.

pg. 2-12.

|||

It now appears that the character after 'pg' is a period. Previously it was a colon.

If it is a period, replace the colon in Manivannan's with a period.

select id,name,substring(pagenumber,charindex(':',pagenumber) +1, charindex('-',pagenumber)-charindex(':',pagenumber)-1)

From

#data

[/quote/

|||i replaced but same error|||

Contrary to your earlier assertion, some of your data does NOT follow the pattern [ pg.n%-n% ].

The error is due to one or more rows NOT containing a dash [-].

Try this query to find the rows that do not have a dash.

SELECT *

FROM MyTable

WHERE MyColumn NOT LIKE '%-%'

|||

THERE are three rows that dont contain a '-'

so what to do

|||

This variation 'should' handle your situation.

All that is required is that the Page Number contain the characters 'pg'. It doesn't matter if there is a colon, a period, a dash, or only the first group of numbers.


Code Snippet

DECLARE @.Data table
( [ID] varchar(20) ,
[Name] varchar(20) ,
[PageNumber] varchar(20)
);


INSERT INTO @.Data VALUES ( '1', 'Gas', 'pg.231-123' );
INSERT INTO @.Data VALUES ( '2', 'Oil', 'pg.323-123' );
INSERT INTO @.Data VALUES ( '3', 'Benzene', 'pg.323' );
INSERT INTO @.Data VALUES ( '4', 'Oxygen', 'pg 323-123' );
INSERT INTO @.Data VALUES ( '5', 'Lubricant', 'pg:323-123' );
INSERT INTO @.Data VALUES ( '6', 'Friction', 'pg. 23' );


SELECT
ID,
Name,
Page = ltrim(substring(PageNumber,(charindex('pg',PageNumber)+3), (isnull(len(PageNumber)-(charindex('pg',PageNumber)+2),0))))
FROM @.Data;

ID Name Page
-- -- --
1 Gas 231-123
2 Oil 323-123
3 Benzene 323
4 Oxygen 323-123
5 Lubricant 323-123
6 Friction 23

|||

need the answer as

id name page

1 gas 231

2 oil 323

etc

|||

This should correct that:

DECLARE @.Data table
( [ID] varchar(20) ,
[Name] varchar(20) ,
[PageNumber] varchar(20)
);


INSERT INTO @.Data VALUES ( '1', 'Gas', 'pg.231-123' );
INSERT INTO @.Data VALUES ( '2', 'Oil', 'pg.323-123' );
INSERT INTO @.Data VALUES ( '3', 'Benzene', 'pg.323' );
INSERT INTO @.Data VALUES ( '4', 'Oxygen', 'pg 323-123' );
INSERT INTO @.Data VALUES ( '5', 'Lubricant', 'pg:323-123' );
INSERT INTO @.Data VALUES ( '6', 'Friction', 'pg. 23' );


SELECT
ID,
Name,
Page = ltrim(substring(PageNumber,(charindex('pg',PageNumber)+3), (isnull(len(PageNumber)-(charindex('-',PageNumber)),0))))

FROM @.Data;

/*

ID Name Page
-- -- --
1 Gas 231
2 Oil 323
3 Benzene 323
4 Oxygen 323
5 Lubricant 323
6 Friction 23

*/

|||

I DONT GET THE CORRECT ANSWER

THE ANSWER I GOT WAS 231-,323- ETC

NEED THE ANSWER AS 231,323

|||

The code supplied immediately above provides the data in the form you requested -UNLESS there is something about the data that you have not clearly communicated. (Carefully examine the sample data included to find out if there is something different about how your data is stored.)

I suggest that you copy the code above to a new query window, and execute it. You 'should' then see that the resulset is as you requested. Then you may substitute your table/column names and 'tweak' it until it works for you.

|||

pp.79-103.
pp.63-78.
pp.45-62.
pp.229-254.
pp.147-164.
pp.75-81.
pp.35-56.
pp.23-33.
pp.5-21.
pp.5-13.
pp.268-282.
pp.257-267.

Friday, February 24, 2012

convert into to hours minutes

Someone else setup the table and I cannot change it, so I am stuck with
what I have.
I have an INT field called hourminute.
The data is 3-4 digits, and is always based on hour/minute in 24-hour
format.
I need the output to be hh:mm. In the field, there is not a COLON and
that is what I need.
I have the following sql query that converts it correctly, but I need to
insert the :
select CONVERT(CHAR(5),hourminute,8)as thetime from booking
Help'
*** Sent via Developersdex http://www.examnotes.net ***SELECT CAST(hourminute / 100 AS char(2)) + ':' + RIGHT(CAST(hourminute AS
char(4)),2)
If you posted to this forum through TechNet, and you found my answers
helpful, please mark them as answers.
"Joey Martin" wrote:

> Someone else setup the table and I cannot change it, so I am stuck with
> what I have.
> I have an INT field called hourminute.
> The data is 3-4 digits, and is always based on hour/minute in 24-hour
> format.
> I need the output to be hh:mm. In the field, there is not a COLON and
> that is what I need.
> I have the following sql query that converts it correctly, but I need to
> insert the :
> select CONVERT(CHAR(5),hourminute,8)as thetime from booking
>
> Help'
>
>
>
> *** Sent via Developersdex http://www.examnotes.net ***
>|||Works if there are 4 digits, but does not work if 3.
Example:
730 = 7 :0
725 = 7 :5
*** Sent via Developersdex http://www.examnotes.net ***|||Hi, Joey
You have used the CONVERT function using 8 for the style argument, but
you specified that the hourminute column is an int. The style argument
is only used if you convert a datetime, smalldatetime, float, real,
money, smallmoney or xml value. For any other data type (including
int), the style argument is ignored. See Books Online topic "CAST and
CONVERT (Transact-SQL)" for more informations.
You probably want to use something like this:
SELECT CONVERT(varchar(2),hourminute/100)+':'
+RIGHT(CONVERT(char(3),hourminute%100+10
0),2)
FROM booking
Razvan|||Hi, Mark
Your query works only for values greater than 1000.
Here is my sample data used for testing:
CREATE TABLE booking (hourminute int)
INSERT INTO booking VALUES (1234)
INSERT INTO booking VALUES (2307)
INSERT INTO booking VALUES (0)
INSERT INTO booking VALUES (105)
INSERT INTO booking VALUES (555)
Razvan|||"Razvan Socol" <rsocol@.gmail.com> wrote in message
news:1137522307.881961.56610@.g49g2000cwa.googlegroups.com...
> Hi, Mark
> Your query works only for values greater than 1000.
> Here is my sample data used for testing:
> CREATE TABLE booking (hourminute int)
> INSERT INTO booking VALUES (1234)
> INSERT INTO booking VALUES (2307)
> INSERT INTO booking VALUES (0)
> INSERT INTO booking VALUES (105)
> INSERT INTO booking VALUES (555)
> Razvan
This is ugly, but it works:
select left(right('000' + cast(hourminute as varchar(4)), 4), 2) + ':' +
right(right('000' + cast(hourminute as varchar(4)), 4), 2) from booking|||"Razvan Socol" <rsocol@.gmail.com> wrote in message
news:1137522307.881961.56610@.g49g2000cwa.googlegroups.com...
> Hi, Mark
> Your query works only for values greater than 1000.
> Here is my sample data used for testing:
> CREATE TABLE booking (hourminute int)
> INSERT INTO booking VALUES (1234)
> INSERT INTO booking VALUES (2307)
> INSERT INTO booking VALUES (0)
> INSERT INTO booking VALUES (105)
> INSERT INTO booking VALUES (555)
> Razvan
Another one:
select STUFF(REPLICATE('0', 4-LEN(hourminute)) + CAST(hourminute as
VARCHAR(4)), 3,0,':') FROM booking|||How about this one:
SELECT STUFF(RIGHT(CAST(hourminute+10000 as CHAR(5)),4),3,0,':')
FROM booking
Razvan|||Nothing fundamentally wrong with arriving at the desired format by using the
disivion; the problem was a result of using char as opposed to varchar.
CASTING the pieces into char was adding extra spaces onto the end, which was
throwing off the result of the RIGHT function.
SELECT CAST(hourminute / 100 AS varchar(2)) + ':' + RIGHT(CAST(hourminute AS
varchar(4)),2) .
This does produce some strange results as well. With ML's supplied sample
data, a hourminute value of 0 returns 0:0 . The below cleans that up:
SELECT
CONVERT(char(10),
CAST(
CAST(hourminute / 100 AS varchar(2)) + ':' + RIGHT(CAST(hourminute AS
varchar(4)),2)
AS datetime)
, 8)
FROM booking
"Joey Martin" wrote:

> Works if there are 4 digits, but does not work if 3.
> Example:
> 730 = 7 :0
> 725 = 7 :5
>
> *** Sent via Developersdex http://www.examnotes.net ***
>|||"Razvan Socol" <rsocol@.gmail.com> wrote in message
news:1137525849.104051.25420@.g43g2000cwa.googlegroups.com...
> How about this one:
> SELECT STUFF(RIGHT(CAST(hourminute+10000 as CHAR(5)),4),3,0,':')
> FROM booking
> Razvan
Good STUFF Razvan. :-)

Sunday, February 19, 2012

Convert Int Values into words..?

Hi,

I'm doing an online invoice system with ASP and MS SQL.

So you got the price and total amount.

And let say the amount is $4000.00 , there is also a portion where the invoice needs to mention it in words, "Fourty Thousand"

Can it be "cast" ? "conver" ? or anything?
Or is there any workaround??$4000.00 = "Fourty Thousand"

I better should be careful while doing any transactions with you ;).

Maybe a function can be written to get it done ... will try it out ...

Highly unlikely you will get a readymade function for the same ...|||Opps..sorry...I was kindy sleepy..:)

thanks...I'll be trying out some code too...so many numbers condition to check in the if then else....|||don't write your own, there are so many scripts out there already, i'm sure you can adapt the logic, even if they aren't all written in wahtever language you plan to use...

http://developer.asna.com/Articles/b000106.asp
http://www.idinews.com/sourcecode/IntegerFunction.html
http://www.mvps.org/access/modules/mdl0001.htm
http://www.vbce.com/code/functions/convert_numbers_to_words/index.asp
http://www.vbexplorer.com/VBExplorer/tips/src36.asp

how did i find these so quickly?

google

Convert INT value to STRING so I can add it to another STRING

I'm trying to figure out how to convert an INT so that I can add it to another string in a statement like
SELECT '<a href="http://links.10026.com/?link=http://mydomain.com/' + [IntValue] + '">' + [LinkName]
Where [IntValue] is an INT field containing a folder number. I tried:

TO_CHAR([IntValue, '999')
but it didn't work. And I tried to find a TO_STRING function, but had no luck.
Any advice to someone who is savy, but new to SQL Queries?

SELECT '<a href="http://links.10026.com/?link=http://mydomain.com/' + STR([IntValue]) + '">' + [LinkName]
HTH
regards

|||Bingo! I had to restrict the function to 3 digits for my purposes, but it worked like a charm.
Thanks a bunch!

Convert Int to Time

I have a DB that gets telephone call information from a telephone switch. We use 3rd part software and a db to capture all of this. However for some reason most of the fields are stored as int DateTime is stored as an int. I am able to convert most of the date field from int by doing select convert(datetime,convert(varchar(8), localday)) that works fine the int are in the db as 20061029 for 10-29-2006.
How ever I can't convert the columns starttime and endtime. They are also stored as int but
They don't seem to store a date.
For instance for the date 9/29/2006 the start time of one particular call is
1159533056 and the endtime is 1159533264 All i need to get from this is the time since I already have the date from another column. I can't figure out what this data represents.
How can I convert this to datetime?

Thanks!

Quote:

"The datetime and smalldatetime data types are stored internally as integers. The datetime data type is stored as a pair of four-bytes integers, which together represent the number of milliseconds since midnight of January 1, 1753. The first four bytes store the date, and the second four bytes store the time. The smalldatetime data type is stored as a pair of two-byte integers, which together represent the number of minutes since midnight on January 1, 1900. The first two bytes store the date, and the second two bytes store the time."

Also, check out this: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_ca-co_2f3o.asp (see the first table on that page).

So, if your columns' data types are datetime or smalldatetime (but not "int", which would be bizarre), you don't need to concern yourself with converting it manually and/or trying to figure out what exactly this integer means. Just call the appropriate version of CONVERT (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_ca-co_2f3o.asp).

|||

It looks to me like your integers are storing number of seconds since the epoch, or 1 January 1970. This is pretty common on UNIX systems. (Cf. http://en.wikipedia.org/wiki/Unix_time)

Try:

declare @.d1 datetime
declare @.d2 datetime
set @.d1 = dateadd(second, 1159533056, '1 January 1970')
set @.d2 = dateadd(second, 1159533264, '1 January 1970')
print @.d1
print @.d2

Result:

Sep 29 2006 12:30PM
Sep 29 2006 12:34PM

Cheers,
-Isaac

|||

Great that did it. yes they are stored as integers. I hate this db everything that is not text is stored as INT I mean Everything.
I have had to create several calculated fields for them. It's 3rd party db if i modify existing colums it won't function.

What would be the best way to create a calculated field for this data?
Thanks again

|||nevermind i got it by doing this...

alter TABLE [CDRMAin] add
[starttimetimecalc] AS dateadd(second, endtime, '1 January 1970')|||I just realized that this code is giving me the proper date from my date that is stored as an int, but it is not giving me the proper time
for this datetime as an int 1163517315
i get 2006-11-14 15:15:15.000, the correct time should be 10:16 am
the code i used to create my table is
alter TABLE [CDRMAin] add
[starttimetimecalc] AS dateadd(second, endtime, '1 January 1970')

how can i correct this.
thanks

Convert Int to Time

I have a DB that gets telephone call information from a telephone switch. We use 3rd part software and a db to capture all of this. However for some reason most of the fields are stored as int DateTime is stored as an int. I am able to convert most of the date field from int by doing select convert(datetime,convert(varchar(8), localday)) that works fine the int are in the db as 20061029 for 10-29-2006.
How ever I can't convert the columns starttime and endtime. They are also stored as int but
They don't seem to store a date.
For instance for the date 9/29/2006 the start time of one particular call is
1159533056 and the endtime is 1159533264 All i need to get from this is the time since I already have the date from another column. I can't figure out what this data represents.
How can I convert this to datetime?

Thanks!

Quote:

"The datetime and smalldatetime data types are stored internally as integers. The datetime data type is stored as a pair of four-bytes integers, which together represent the number of milliseconds since midnight of January 1, 1753. The first four bytes store the date, and the second four bytes store the time. The smalldatetime data type is stored as a pair of two-byte integers, which together represent the number of minutes since midnight on January 1, 1900. The first two bytes store the date, and the second two bytes store the time."

Also, check out this: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_ca-co_2f3o.asp (see the first table on that page).

So, if your columns' data types are datetime or smalldatetime (but not "int", which would be bizarre), you don't need to concern yourself with converting it manually and/or trying to figure out what exactly this integer means. Just call the appropriate version of CONVERT (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_ca-co_2f3o.asp).

|||

It looks to me like your integers are storing number of seconds since the epoch, or 1 January 1970. This is pretty common on UNIX systems. (Cf. http://en.wikipedia.org/wiki/Unix_time)

Try:

declare @.d1 datetime
declare @.d2 datetime
set @.d1 = dateadd(second, 1159533056, '1 January 1970')
set @.d2 = dateadd(second, 1159533264, '1 January 1970')
print @.d1
print @.d2

Result:

Sep 29 2006 12:30PM
Sep 29 2006 12:34PM

Cheers,
-Isaac

|||

Great that did it. yes they are stored as integers. I hate this db everything that is not text is stored as INT I mean Everything.
I have had to create several calculated fields for them. It's 3rd party db if i modify existing colums it won't function.

What would be the best way to create a calculated field for this data?
Thanks again

|||nevermind i got it by doing this...

alter TABLE [CDRMAin] add
[starttimetimecalc] AS dateadd(second, endtime, '1 January 1970')|||I just realized that this code is giving me the proper date from my date that is stored as an int, but it is not giving me the proper time
for this datetime as an int 1163517315
i get 2006-11-14 15:15:15.000, the correct time should be 10:16 am
the code i used to create my table is
alter TABLE [CDRMAin] add
[starttimetimecalc] AS dateadd(second, endtime, '1 January 1970')

how can i correct this.
thanks