Showing posts with label converting. Show all posts
Showing posts with label converting. Show all posts

Sunday, March 11, 2012

error converting varchar to numeric

i have a huge stored procedure abt 500 lines..and i am calling this sp from an asp.net page...thn i got this error - error converting varchar to numeric - and am trying to debug...is there any way we can find out where the error is coming from...like aproxly which line number..etcor do i have to go through each line manually and see where i am doing the conversion...

thanksNever tried it myself but it should let you step through a sproc like you would your C#/VB.Net code behind.

Walkthrough: Debugging Hello World, a SQL Stored Procedure|||hi MMS

I was able to isolate the line tht was causing the problem..however i will go through the article to see if it will help with some info for future use.

thanks.

Error converting Varchar to Int - SQL 2000

Hello, I'm having problems with this piece of Transact SQL. What I
need to do is to get a date 2 months ahead of an entered date.
However, I am not supposed to use this: @.dt+60 (in order to get 60 days
exactly). Consequently, if I've entered '12/21/05' as the original
date, I need to get the 2 month date as '2/21/06' regardless if they're
60 days or not. As you can see, the only thing that the new date will
be changed is going to be the month. Thus, the dates would convert as
follows: '5/5/05' to '7/5/05', '2/21/05' to '4/21/05' and so on except
for the months 11 and 12, which in that case would be 1 and 2 of the
following year.
This is what I have so far.
DECLARE @.dt DATETIME
DECLARE @.2dt VARCHAR
SET @.dt = '12/14/06'
SET @.2dt =
CASE
WHEN DATEPART(mm, @.dt) =11 THEN '11/' & DATEPART(dd,@.dt) + '/' &
DATEPART(yy,@.dt)+1
WHEN DATEPART(mm, @.dt) =12 THEN '12/' & DATEPART(dd,@.dt) + '/' &
DATEPART(yy,@.dt)+1
ELSE DATEPART(mm, @.dt) +2 & '/' & DATEPART(dd,@.dt) + '/' &
DATEPART(yy,@.dt)
END
print @.2dt
When I test it in the query analyzer, I get the this error: Syntax
error converting the varchar value '12/' to a column of data type int.
I tried to use the CAST and CONVERT function, it did not work. Perhaps
I was doing it wrong.
Any help would be appreciated.Doesn't this work for you?
DECLARE @.dt DATETIME
DECLARE @.2dt datetime
SET @.dt = '12/14/06'
SET @.2dt = dateadd(m,2,@.dt)
print convert(varchar,@.2dt)
http://sqlservercode.blogspot.com/|||Gosh! Thank you! This is exactly what I was looking for! You're a
genius!
I had this code as part of an Access query that I needed to convert to
SQL 2000 and it was driving me crazy. I'm so glad SQL has a function
that does this.
Thanks again!
JR
SQL wrote:
> Doesn't this work for you?
> DECLARE @.dt DATETIME
> DECLARE @.2dt datetime
> SET @.dt = '12/14/06'
> SET @.2dt = dateadd(m,2,@.dt)
> print convert(varchar,@.2dt)
>
> http://sqlservercode.blogspot.com/|||note: the reason for the error is that the '&' operator in sql is the
bitwise AND operator - not a string concatenation operator
so it was trying to convert '12/' to an int before performing the
bitwise AND.
ILCSP@.NETZERO.NET wrote:
> Hello, I'm having problems with this piece of Transact SQL. What I
> need to do is to get a date 2 months ahead of an entered date.
> However, I am not supposed to use this: @.dt+60 (in order to get 60 days
> exactly). Consequently, if I've entered '12/21/05' as the original
> date, I need to get the 2 month date as '2/21/06' regardless if they're
> 60 days or not. As you can see, the only thing that the new date will
> be changed is going to be the month. Thus, the dates would convert as
> follows: '5/5/05' to '7/5/05', '2/21/05' to '4/21/05' and so on except
> for the months 11 and 12, which in that case would be 1 and 2 of the
> following year.
> This is what I have so far.
> DECLARE @.dt DATETIME
> DECLARE @.2dt VARCHAR
> SET @.dt = '12/14/06'
> SET @.2dt =
> CASE
> WHEN DATEPART(mm, @.dt) =11 THEN '11/' & DATEPART(dd,@.dt) + '/' &
> DATEPART(yy,@.dt)+1
> WHEN DATEPART(mm, @.dt) =12 THEN '12/' & DATEPART(dd,@.dt) + '/' &
> DATEPART(yy,@.dt)+1
> ELSE DATEPART(mm, @.dt) +2 & '/' & DATEPART(dd,@.dt) + '/' &
> DATEPART(yy,@.dt)
> END
>
> print @.2dt
>
> When I test it in the query analyzer, I get the this error: Syntax
> error converting the varchar value '12/' to a column of data type int.
> I tried to use the CAST and CONVERT function, it did not work. Perhaps
> I was doing it wrong.
> Any help would be appreciated.
>

Error converting to DateTime/SmallDateTime

I am trying to add some datetime values into a table. However, the database keeps throwing the following error "The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value."

The code is as follows:

string start = dateCal.SelectedDate.ToString().Substring(0, 10) + " " + startTB.Text;

string end = dateCal.SelectedDate.ToString().Substring(0, 10) + " " + endTB.Text;

//DateTime starts = Convert.ToDateTime(start);

//DateTime ends = Convert.ToDateTime(end);

sqlInsert.CommandText = "INSERT INTO aspnet_reportdate VALUES ('" + refno + "', '" + start + "', '" + end + "')";

where startTB and endTB contains a time in valid format (HH:MM)

The same error would occur even if I converted the string to a DateTime object before I try to insert it into the database.

a sample value of start would be "6/19/2007 10:00"

What puzzles me is that only the error is only thrown by the database (SQL Server Express) but not C#

I have tried using both datetime and smalldatetime for the columns in question in the database also.

There is no problem with your SQL Server or C#. The problem is on your input data (mismatched date format).

I strongly recommand to change your code as follow as. It is really very dangerous code you are writing (SQL Injuction).

Don't use Dynamic Query generation on the UI. Beaware of SQL Injunction. (use parameters or Stored Procs)

The following code will work for you, (the sql server parse the param before executing it, so you can easily identify the problem)

Code Snippet

sqlInsert.CommandText = "INSERT INTO aspnet_reportdate VALUES (@.refno, @.start, @.end)";

sqlInsert.Parameters.Add(new SqlParameter("@.refno", DbType.String));

sqlInsert.Parameters.Add(new SqlParameter("@.start", DbType.DateTime));

sqlInsert.Parameters.Add(new SqlParameter("@.end", DbType.DateTime));

sqlInsert.Parameters[0].Value = refno;

sqlInsert.Parameters[1].Value = starts;

sqlInsert.Parameters[2].Value = ends;

sqlInsert.ExecuteNonQuery();

|||

Just to add to what Mani has said, if you do this kind of thing, the best way to get help is to add a print statement, messagebox, etc and print out the SQL statement that you are trying to execute. You can't use profiler with express (at least not with a license to the real tools), but if you can, using profiler you can see the statement that you are trying to execute. I would strongly consider purchasing a developer license to get the tools to work with. Like Mani says, use a parameterized statement in all cases possible, but if you are trying to build a reproducible script, that might not be possible.

The first most important step in a process like this is to figure out what you are trying to execute and take that statement to Management Studio (Express will do for this) and work out what the issue is in the query.

Date values should ideally use the standard formats. Look up "datetime data type, formats" in the index, and check out the ODBC timestamp format. It will always work.

|||

thx all for the help

just a further question. what is sql injunction and what problems does it bring about?

couldn't seem to find anything substantial on it

|||

Louis Davidson wrote:

Just to add to what Mani has said, if you do this kind of thing, the best way to get help is to add a print statement, messagebox, etc and print out the SQL statement that you are trying to execute. You can't use profiler with express (at least not with a license to the real tools), but if you can, using profiler you can see the statement that you are trying to execute. I would strongly consider purchasing a developer license to get the tools to work with. Like Mani says, use a parameterized statement in all cases possible, but if you are trying to build a reproducible script, that might not be possible.

will bear this in mind

most of what i do now is more for interest or sch work, so my choice of tools are more restricted.

error converting the char value BUT IT IS A CHAR ALREADY

SQL Server 2000 SP3a
Access 2000 SP3 (using adp)
Im going mildly loopy, hopefully someone can aid my sanity.
Table in SQL Server had a column (column_a tinyint), data contained is just
ones and zeros. In Enterprise Manager I changed the data type of column_a t
o
char(1), so that I could then go and replace the ones and zeros with 'Y' and
'N'
When I try and change one of the values, through either Access or Enterprise
Manager, it errors with:
"Syntax error converting the char value 'Y' to a column of data type int"
I don't understand, I've changed the columns data type from tinyint to
char(1), so surely these updates should work. Whats the problem with this?
I've taken the db offline, I've even tried booting the server (clutching at
straws). What might not have been updated correctly?
Any suggestions would be great!
Its these stupid things which should be a two second job, but end up taking
me hours. And yes, if I'd got it right in the first instance, then this
wouldn't have been a problem :)
Thanks for any replies.I would have thought that the logical way to proceed would have been:
1. Add a field of Char(1) to the table with a different name than the source
field
2. Update this new field to 'Y' and 'N' based on the source field's values
3. Remove the source field
4. Rename the new field to that of the source field.
I'm surprised that SQLEM would even let you change a TinyInt to a Char in th
e
first place. If it did, what values are in that field?
Thomas|||1- Be sure it has been changed. See deifnition using view
information_schema.columns
2 - Try doing the update from query analyzer.
update table1
set colB = substring('NY', cast(colB as int) + 1, 1)
AMB
"Steve'o" wrote:

> SQL Server 2000 SP3a
> Access 2000 SP3 (using adp)
> Im going mildly loopy, hopefully someone can aid my sanity.
> Table in SQL Server had a column (column_a tinyint), data contained is jus
t
> ones and zeros. In Enterprise Manager I changed the data type of column_a
to
> char(1), so that I could then go and replace the ones and zeros with 'Y' a
nd
> 'N'
> When I try and change one of the values, through either Access or Enterpri
se
> Manager, it errors with:
> "Syntax error converting the char value 'Y' to a column of data type int"
> I don't understand, I've changed the columns data type from tinyint to
> char(1), so surely these updates should work. Whats the problem with this
?
> I've taken the db offline, I've even tried booting the server (clutching a
t
> straws). What might not have been updated correctly?
> Any suggestions would be great!
> Its these stupid things which should be a two second job, but end up takin
g
> me hours. And yes, if I'd got it right in the first instance, then this
> wouldn't have been a problem :)
> Thanks for any replies.|||> Table in SQL Server had a column (column_a tinyint), data contained is
just
> ones and zeros. In Enterprise Manager I changed the data type of column_a
to
> char(1), so that I could then go and replace the ones and zeros with 'Y'
and
> 'N'
> When I try and change one of the values, through either Access or
Enterprise
> Manager, it errors with:
> "Syntax error converting the char value 'Y' to a column of data type int"
While I don't have any obvious suggestion to help with EM, Access has a bit
of odd behavior. If you "Link" a SQL Server table into an Access database,
Access "remembers" the schema of the table, so that if you then do something
to the schema of the SQL Server table, Access is not aware of the change.
The workaround that I have used is to delete the linked table in Access and
re-link to it. I also like to rename it to get rid of the stupid "dbo_"
prefix that Access adds.
--
Peace & happy computing,
Mike Labosh, MCSD
"Escriba coda ergo sum." -- vbSensei|||Wow, several replies, thanks.
Thomas
I did not mention this, but there are several triggers and check consraints,
basically several dependencies to the column_a. I did try creating a new
column_a_new (char1), then tried renaming column_a to column_a_old, but it
wasn't having it because of the dependencies. In an Access .mdb you can get
away with this, but sql server appears a bit more rigid in this type of
workaround.
Alejandro
I made the changes a few days ago (I have been trying to fix it in that
time) and the server and cient machine have been booted a few times.
I double checked information_scheme.columns, great suggestion thanks, and
got this which seems a little odd to me as I set it to char(1), which is doe
s
display as in Access and EM.
ORDINAL_POSITION
16
COLUMN_DEFAULT
('N')
IS_NULLABLE
No
DATA_TYPE
nvarchar
CHARACTER_MAXIMUM_LENGTH
50
CHARACTER_OCTET_LENGTH
100
QA gives the same error when doing an update set
Server: Msg 245, Level 16, State 1, Line 1
Syntax error converting the varchar value 'N' to a column of data type int.
Mike
Yeah, there are lots of little tricks which need to be remembered with
Access (especially 2000) and SQL Server :)
I am using an .adp which is a bit different to an .mdb with linked tables,
but F5 is definitely your freind :)
I have booted the client and server, as I've been messing around for a few
days, so it should be refreshed. And it occurs in EM+QA too.
Thanks to all replies, its sounding horribly like Im going to have to drop
all dependencies, then re-create them after deleting the old column and
adding a new one. Maybe use EM to create a .sql script of the objects
including drop_all first, then alter the script to use char, then run
it....What a hassle, certainly won't make this mistake again, hopefully ;)
PS, is it better to reply to each individual post, or top post with a msg
like this, or bottom post with a msg like this ie including replies to
several people?
Or does it not really matter?
"Mike Labosh" wrote:

> just
> to
> and
> Enterprise
> While I don't have any obvious suggestion to help with EM, Access has a bi
t
> of odd behavior. If you "Link" a SQL Server table into an Access database
,
> Access "remembers" the schema of the table, so that if you then do somethi
ng
> to the schema of the SQL Server table, Access is not aware of the change.
> The workaround that I have used is to delete the linked table in Access an
d
> re-link to it. I also like to rename it to get rid of the stupid "dbo_"
> prefix that Access adds.
> --
> Peace & happy computing,
> Mike Labosh, MCSD
> "Escriba coda ergo sum." -- vbSensei
>
>|||> I did not mention this, but there are several triggers and check consraints,d">
> basically several dependencies to the column_a. I did try creating a new
> column_a_new (char1), then tried renaming column_a to column_a_old, but it
> wasn't having it because of the dependencies. In an Access .mdb you can g
et
> away with this, but sql server appears a bit more rigid in this type of
> workaround.
The obvious answer is to drop the triggers and check constraints before you
run
through the steps I suggested and then re-add the triggers and check constra
ints
afterwards. It's not that difficult. You can use the query analyzer to scrip
t
the creation of the appropriate triggers and check constraints as well as sc
ript
the drop scripts for these. Besides, it is likely that these triggers and ch
eck
constraints need to change anyway.

> PS, is it better to reply to each individual post, or top post with a msg
> like this, or bottom post with a msg like this ie including replies to
> several people?
> Or does it not really matter?
Doubt it matters much.
Thomas|||On Mon, 11 Apr 2005 10:00:01 -0700, Steve'o wrote:

>PS, is it better to reply to each individual post, or top post with a msg
>like this, or bottom post with a msg like this ie including replies to
>several people?
>Or does it not really matter?
Hi Steve'o,
Trying to start a flame-war? <grin>
Top-posting vs bottom-posting can turn into a heated debate. I believe
that most Usenet regulars prefer bottom-posting or inline reply (quote,
reply, quote, reply, ...). However, MS Outlook defaults to top-posting,
as does (if I recall correctly) MS' internet portal to the MS related
groups.
Since this group is about an MS product, a relatively large number of
users use Outlook or MS' internet portal for access. As a result, you'll
see lots of top-posting here.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

error converting nvarchar to int


I have this stored procedure and am getting errors.
I filtered on Info = 'I' which should only have numeric values. I have some
info with Info = 'L' that does have alpha code.
I have tried the case below but am still having problems.
Any help appreciated
CREATE PROCEDURE NTF_UpdateInfoAfterPost
@.orderNo varchar(30),
@.rUser int
AS
--Used to delete the Info messages from all users.
--Typically used before creating a new info message
update Notify
Set
signed = 4,
rUser = @.rUser,
DateSigned = GetDate()
where (Info = 'I' and Info is not null) and orderNo = Case When
isNumeric(@.OrderNo) = 1 then @.OrderNo Else 0 End
Stephen K. MiyasatoHi
Try
update Notify
Set
signed = 4,
rUser = @.rUser,
DateSigned = GetDate()
where (Info = 'I' and Info is not null) and orderNo = Case When
isNumeric(@.OrderNo) = 1 then @.OrderNo Else '0' End
"Stephen K. Miyasato" <miyasat@.flex.com> wrote in message
news:%23IxODu4gGHA.1792@.TK2MSFTNGP03.phx.gbl...
>
> I have this stored procedure and am getting errors.
> I filtered on Info = 'I' which should only have numeric values. I have
> some info with Info = 'L' that does have alpha code.
> I have tried the case below but am still having problems.
> Any help appreciated
>
> CREATE PROCEDURE NTF_UpdateInfoAfterPost
> @.orderNo varchar(30),
> @.rUser int
> AS
> --Used to delete the Info messages from all users.
> --Typically used before creating a new info message
> update Notify
> Set
> signed = 4,
> rUser = @.rUser,
> DateSigned = GetDate()
> where (Info = 'I' and Info is not null) and orderNo = Case When
> isNumeric(@.OrderNo) = 1 then @.OrderNo Else 0 End
> Stephen K. Miyasato
>

error converting date time

Hi i m tring to convert a date time

declare @.a datetime
declare @.b varchar(10)
set @.b='26/04/2004'
set @.a= Convert(datetime, @.b)

but it gives me this error:

Server: Msg 242, Level 16, State 3, Line 5
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.

I believe is my date format..i want to know how to make sure that i am the dd/mm/yyyy format is correct way?Why are you sending the date in as a varchar ?|||Use SET DATEFORMAT

Sets the order of the dateparts (month/day/year) for entering datetime or smalldatetime data.|||Hi,
thanks for all ur reply.. basically i wanted to send date in as dateTime but i cant because i cant assign a date to null so i have to send it to my database and from there i convert it to valid date time.

Thanks alot.

Error converting datatypes

Hi,

This script gets run by a job every 3 mins, and it's falling over with an "Error converting varchar value... to column of datatype int", and I think it's on this line:

select @.sbj1='New ICNA Forum Post (ThreadID='+@.existingID+')'

...where I'm trying to build up a string by dropping an ID number (datatype int) into it.

So I tried:

select @.sbj1='New ICNA Forum Post (ThreadID='+CAST(@.existingID AS varchar(100))+')'

and:

select @.sbj1='New ICNA Forum Post (ThreadID='+CONVERT(varchar(100), @.existingID)+')'

Both of these result in the job running successfully, but no emails get sent and the job history shows the error "Incorrect syntax near 'Forum'." On the good side, it's supposed to be looping through the email-sending bit 4 times (there are currently 4 users) and sure enough, it repeats that error message 4 times.

The full script follows below. I'd be hugely grateful if anyone could point out what I'm doing wrong, and how to do it right.

Cheers.

Declare @.hMessage varchar(255),@.msg_id varchar(255)
Declare @.MessageText varchar(8000),@.message varchar(8000)
Declare @.MessageSubject varchar(8000),@.subject varchar(8000)
Declare @.Origin varchar (8000), @.originator_address varchar(8000)

EXEC master.dbo.xp_findnextmsg @.unread_only='true',@.msg_id=@.hMessage OUT

WHILE @.hMessage IS NOT NULL
BEGIN

exec master.dbo.xp_readmail
@.msg_id=@.hMessage,
@.message=@.MessageText OUT,
@.subject=@.MessageSubject OUT,
@.originator_address=@.Origin OUT

IF ((SELECT COUNT(*) FROM forum_users WHERE email = @.Origin) = 1) -- IF email from forum-recognised address
BEGIN
IF (CHARINDEX('(ThreadID=', @.MessageSubject)>0) -- IF email has a thread ID
BEGIN
DECLARE @.existingID int, @.em1 varchar(100), @.bdy1 varchar(8000), @.sbj1 varchar(500)
SELECT @.existingID=CAST(SUBSTRING(@.MessageSubject, (CHARINDEX('=', @.MessageSubject)+1), (CHARINDEX(')', @.MessageSubject)-(CHARINDEX('=', @.MessageSubject)+1))) AS int)
INSERT INTO forum_posts (body, thread_id) VALUES (@.MessageText, @.existingID)

-- Do mailing

declare em_cursor1 cursor for
SELECT email FROM forum_users WHERE email_option='yes'
open em_cursor1
fetch next from em_cursor1
into @.em1

while @.@.FETCH_STATUS=0
begin
select @.bdy1='New ICNA Forum Post:'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+@.Messag eText
select @.sbj1='New ICNA Forum Post (ThreadID='+@.existingID+')'
exec master.dbo.xp_sendmail @.em1,@.bdy1,@.sbj1
fetch next from em_cursor1
into @.em1
end
close em_cursor1
deallocate em_cursor1

END
ELSE -- IF email has no thread ID
BEGIN
DECLARE @.newID int, @.em2 varchar(100), @.bdy2 varchar(8000), @.sbj2 varchar(500) -- Create a new thread record and use the resulting ID to add a thread_post record
INSERT INTO forum_threads (subject) VALUES (@.MessageSubject)
SELECT @.newID=@.@.IDENTITY
INSERT INTO forum_posts (body, thread_id) VALUES (@.MessageText, @.newID)

-- Do mailing

declare em_cursor2 cursor for
SELECT email FROM forum_users WHERE email_option='yes'
open em_cursor2
fetch next from em_cursor2
into @.em2

while @.@.FETCH_STATUS=0
begin
select @.bdy2='New ICNA Forum Post:'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+@.Messag eText
select @.sbj2='New ICNA Forum Post (ThreadID='+@.newID+')'
exec master.dbo.xp_sendmail @.em2,@.bdy2,@.sbj2
fetch next from em_cursor2
into @.em2
end
close em_cursor2
deallocate em_cursor2

END
END

SET @.hMessage = NULL

EXEC master.dbo.xp_findnextmsg @.unread_only='true',@.msg_id=@.hMessage OUT
ENDHave you tried substituing the xp_sendmail with SELECT just to see if you have formatted very thing correctly.|||Ah. Did I mention that my grasp of SQL and its debugging techniques was a little sparse?

Thanks very much for your help, but could you possibly explain how do do that?

Cheers.|||OK;

In your script you have a line like:
exec master.dbo.xp_sendmail @.em1,@.bdy1,@.sbj1
RewriteSELECT 'master.dbo.xp_sendmail', @.em1,@.bdy1,@.sbj1
Do this for all xp_sendmail. This may shine some light.|||Aha! Well, at least I've learnt how to get some debugging output. Unfortunately I'm none the wiser as to why sendmail isn't working.

It loops 4 times, once for each email address in my forum_users table. I'm sending the "trigger" email from a hotmail address (needs to be external to our network) and thus for each email it tries to send the subject and body look like:

@.sbj1:
New ICNA Forum Post (ThreadID=24)

@.bdy1:
New ICNA Forum Post: Friday morning test 1 __________________________________________________ _______________ Join the worlds largest e-mail service with MSN Hotmail. http://www.hotmail.com

Which are pretty well exactly what I was expecting - so why on earth is it falling over? :(|||At last, got it working! It didn't like this line:

exec master.dbo.xp_sendmail @.em1,@.bdy1,@.sbj1

when I replaced it with:

exec master.dbo.xp_sendmail
@.recipients=@.em1,
@.message=@.bdy1,
@.subject=@.sbj1

it worked fine. I don't know why, and I don't care :) It works...

error converting datatypes

Hello,

Firstly, i need to work out why I cannot change my datatypes(please see query)

Code Snippet

SELECT * FROM (

SELECT top 10

ref,

RecordDate,

TransactionID,

StatusChangedTimeStamp,

TransactionStatus,

PartyTransactionStatus,

BadDeliveryReason,

TradingDaysRef

FROM (

SELECT 1 seq,

'ref' ref,

'RecordDate' RecordDate,

'TransactionID' TransactionID,

'TransactionStatus' TransactionStatus,

'StatusChangedTimeStamp' StatusChangedTimeStamp,

'PartyTransactionStatus' PartyTransactionStatus,

'BadDeliveryReason' BadDeliveryReason,

'TradingDaysRef' TradingDaysRef

UNION ALL

SELECT 2 seq,

cast(ref as bigint),

RecordDate,

TransactionID,

StatusChangedTimeStamp,

TransactionStatus,

PartyTransactionStatus,

BadDeliveryReason,

TradingDaysRef

FROM dbo.ParticipantTradeStatusChange

) x

order by seq, RecordDate

) y

The error returned is:

Server: Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to bigint.

The reason for me doing this, is exporting both column names & data to a xls file.

Secondly, once i get the query to complete...I kindly ask, how would i make this query a little swifter in which, i mean, select the top 100 from the table then SELECT the columns...when i do

SELECT top 10 * FROM (

SELECT *

It falls over and dies

Help much appreciated

thanks,

i

The data -- literals -- that you have above your unions are not implicitly compatible with what is below the union. Look at this example:

Code Snippet

select 'Header'
union all
select 2

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

I am basically getting the same error. You may need to explicitly declare the datatype of the lower part of the union to have them go as varchar -- maybe like:


Code Snippet

select 'Header' as Data
union all
select cast (2 as varchar)

/*
Data
Header
2
*/

|||

i've done a dirty workaround..

simply used cast(columnname as varchar(4000))

did the trick and i have my bcp file with headings Smile

all todo now is make it run faster...

Error converting data type varchar to numeric.

DECLARE @.ENTITY nvarchar (100)

set @.ENTITY = 'AccidentDimension'

DECLARE @.FIELD nvarchar (100)

set @.FIELD = 'JurisdictionState'

DECLARE @.KEYID nvarchar (100)

SET @.KEYID = '1234567890'

DECLARE @.VALUE nvarchar (100)

SET @.VALUE = 'WI'

DECLARE @.WC_TABLE NVARCHAR(100)

SET @.WC_TABLE = 'WorkingCopyAdd' + @.ENTITY

DECLARE @.SQL1 NVARCHAR (1000)

SET @.SQL1 = 'INSERT INTO ' + @.WC_TABLE+ ' (Claim, '+ @.Field +') VALUES ('''+ @.KEYID +''', '''+@.VALUE+''')'

EXECUTE sp_executesql @.SQL1

Can somebody help me. I get this error:

Error converting data type varchar to numeric.

while executing this Dynamic TSQl Command

Odd; what is the data type of the "JurisdictionState" column. The other column should be fine, but also what is the data type of the "Claim" column.

|||

The statement you are executing is

INSERT INTO WorkingCopyAddAccidentDimension (Claim, JurisdictionState) VALUES ('1234567890', 'WI')

There is a bigger question than the varchar/numeric conversion, and that is why you are using dynamic SQL, but to answer the question you asked, it doesn't look like there should be a problem. Is this the exact code that is failing, or might it be failing on another @.KEYID value?

I suggest you look at www.sommarskog.se/dynamic_sql.html for more on dynamic SQL, even thought it's tangential to your specific question here.

Steve Kass

Drew University

http://www.stevekass.com

|||

Claim is of type: varchar

JurisdictionState is char of length 2

I seperated and inserted with each colunm at a time to know if its problem with Claim or JursidictionState. Well, both of the time I received same error.

|||The error may be caused by an incorrect default, as in teh following sample:

CREATE TABLE a(i int, j INT DEFAULT('acs'))
GO
INSERT a(i)VALUES(1)

also the error might be caused by a trigger. Do you have triggers on the table?|||

Well I had DEFAULT ' ' (A Blank / Space)

Is this the problem ?

|||

yes.. yes..

Always try to stick with the column datatype while giving the default value..

I am really wondering how SQL Server allows to create the default value with different datatype..

|||

CREATE TABLE WCAddAcciDim

([Claim] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS DEFAULT ' ',

[JurisdictionState] [char](2) COLLATE SQL_Latin1_General_CP1_CI_AS DEFAULT ' '

)

GO

INSERT dbo.WCAddAcciDim(Claim , JurisdictionState)VALUES('12', 'IN')

INSERT dbo.WCAddAcciDim(Claim , JurisdictionState)VALUES('1234567890', 'WI')

select * from WCAddAcciDim

DROP TABLE WCAddAcciDim

Well I see no problem when I execute this.

And when I execute this below line, just this line, without use of Dynamic SQL

INSERT dbo.WorkingCopyAddAccidentDimension(Claim, JurisdictionState) VALUES ('1234567890', 'WI')

I get error.

Very Strange.

I created teh table WorkingCopyAddAccidentDimension same way as I did above, infact I copied those lines and rename the tabel name thats it.

What might be the Hidden error, Any idea please

|||

What is the error message you are getting… Verify the table schema using..

Sp_help WorkingCopyAddAccidentDimensiona

|||

Mani:

When I removed the Defaults I was able to update and Insert as wanted and required. However i have NULLS in the rest of colunm. This table has 68 Colunms and I have multiple tables around 6of similar number of colunms. Now I am using the data from these Staging/ WorkingCopy tables and Inserting it back to main Table. Where certain colunm cannot be null. If there is a null in certain colunm it will not allow me to insert it. Thast why I chose to make BLANK as a default in WorkingCopy Table.

Now that I have remove BLANK/ SPACE from teh default, is there any Standard way of Replacing these NULLS with the Blank /Space. Could you please suggest any way to do this?

What does MS SQL Standards have to say on this?

What I could think of is to replace each colunm with a space were ever there is NULL but I guess this is not the standard way of doing. Any suggestion or any modification on re-creating WorkingCopy Table with Defaults?

|||

You are in wrong direction, The default won’t help you here..

The default only activated when you have no entry on the INSERT statement. When you try to INSERT the NULL value the Default value will not be taken, rather it will store as NULL.

In single word, the DEFAULT value only stored when there is no value/no entry specified in the insert query…

As per the BOL,

Column definition

No entry, no DEFAULT definition

No entry, DEFAULT definition

Enter a null value

Allows null values

NULL

Default value

NULL

Disallows null values

Error

Default value

Error

So, you have to use the ISNULL function to fix your problem.

Code Snippet

Create table #Staging1

(

Id int,

Name varchar(10)

)

Insert Into #Staging1 Values(1, NULL);

Insert Into #Staging1 Values(1, 'test');

Go

Create table #Main

(

ID int NOT NULL,

Name varchar(10) NOT NULL DEFAULT ('')

);

--Will Work Fine

Insert Into #Main(ID)

Select ID From #Staging1

--Should Fail

Insert Into #Main(ID,Name)

Select ID,Name From #Staging1

--Will Work

Insert Into #Main(ID,Name)

Select ID,Isnull(Name,'') From #Staging1

|||

Excellent

Got it

Thanks a lot Mani

Error converting data type varchar to numeric.

HI
i have a very big problem.
i have a cloumn name Revenue and i have differt types of revenue in it such as A, B, C.
what i want to do is that i want to say that when the Revenue column is A then sum the tola mount and put in in a new column name A when b then again same thing.
this is my code

case when Revenue='A' then Sum(total_amt) else ' ' end as A

but it is giving me and error Error converting data type varchar to numeric.
please help

Quote:

Originally Posted by voroojak

HI
i have a very big problem.
i have a cloumn name Revenue and i have differt types of revenue in it such as A, B, C.
what i want to do is that i want to say that when the Revenue column is A then sum the tola mount and put in in a new column name A when b then again same thing.
this is my code

case when Revenue='A' then Sum(total_amt) else ' ' end as A

but it is giving me and error Error converting data type varchar to numeric.
please help


first, why the error.

because your case statement said when revenue = 'A' return the sum of total_amt else return blank...the case statement should return (the then part and the else part) the same datatype or at least can be converted to the same datatype.

try ...else sum(0) end as A, ...or ....else 0 end as A

Error converting data type varchar to numeric.

Server: Msg 8114, Level 16, State 5
Error converting data type varchar to numeric.

Hello...
I new in MS SQL.
Given: 2 servers, same SQL statements, same input, same tables, same data types, same triggers.
Problem: One server works fine while the other returns the error above.

I have no idea of the problem why the other is working.IN addition to that, they also have the same MS SQL version.|||Perhaps you could post the relevant code, as well as the table structure? It would be quite impossible to help without these two crucial pieces of information.

Error converting data type varchar to numeric.

Hello,
I cannot get the following Insert Command work. I get the error:
Error converting data type varchar to numeric.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Error converting
data type varchar to numeric.
However 'rate' and 'maximum' variables are declared as Decimal
Dim rate As Decimal
Dim maximumAs Decimal
SqlDataSource1.InsertCommand = "INSERT INTO Example(userName, rate,
maximum, ticket) VALUES('blabla','" & rate & "','" & maximum & "','" &
RadioButtonList1.SelectedValue & "')"
SqlDataSource1.Insert()
CREATE TABLE Example(
userName nvarchar(50),
rate decimal(2, 2),
maximum decimal(6, 2),
ticket nchar(1)
)Try dropping the string delimiters (single quotes). Something like;
"INSERT INTO Example(userName, rate,
maximum, ticket) VALUES('blabla'," & rate & "," & maximum & ",'" &
RadioButtonList1.SelectedValue & "')"
--
Regards,
Dave Patrick ...Please no email replies - reply in newsgroup.
Microsoft Certified Professional
Microsoft MVP [Windows]
http://www.microsoft.com/protect
"Dot Net Daddy" wrote:
| Hello,
|
| I cannot get the following Insert Command work. I get the error:
|
|
| Error converting data type varchar to numeric.
| Description: An unhandled exception occurred during the execution of
| the current web request. Please review the stack trace for more
| information about the error and where it originated in the code.
|
|
| Exception Details: System.Data.SqlClient.SqlException: Error converting
|
| data type varchar to numeric.
|
|
| However 'rate' and 'maximum' variables are declared as Decimal
|
|
| Dim rate As Decimal
| Dim maximumAs Decimal
|
|
| SqlDataSource1.InsertCommand = "INSERT INTO Example(userName, rate,
| maximum, ticket) VALUES('blabla','" & rate & "','" & maximum & "','" &
| RadioButtonList1.SelectedValue & "')"
|
|
| SqlDataSource1.Insert()
|
|
| CREATE TABLE Example(
| userName nvarchar(50),
| rate decimal(2, 2),
| maximum decimal(6, 2),
| ticket nchar(1)
| )
||||Hi,
Already tried that. But this time I got the error:
There are fewer columns in the INSERT statement than values specified
in the VALUES clause. The number of values in the VALUES clause must
match the number of columns specified in the INSERT statement.
Dave Patrick wrote:
> Try dropping the string delimiters (single quotes). Something like;
> "INSERT INTO Example(userName, rate,
> maximum, ticket) VALUES('blabla'," & rate & "," & maximum & ",'" &
> RadioButtonList1.SelectedValue & "')"
> --
> Regards,
> Dave Patrick ...Please no email replies - reply in newsgroup.
> Microsoft Certified Professional
> Microsoft MVP [Windows]
> http://www.microsoft.com/protect
> "Dot Net Daddy" wrote:
> | Hello,
> |
> | I cannot get the following Insert Command work. I get the error:
> |
> |
> | Error converting data type varchar to numeric.
> | Description: An unhandled exception occurred during the execution of
> | the current web request. Please review the stack trace for more
> | information about the error and where it originated in the code.
> |
> |
> | Exception Details: System.Data.SqlClient.SqlException: Error converting
> |
> | data type varchar to numeric.
> |
> |
> | However 'rate' and 'maximum' variables are declared as Decimal
> |
> |
> | Dim rate As Decimal
> | Dim maximumAs Decimal
> |
> |
> | SqlDataSource1.InsertCommand = "INSERT INTO Example(userName, rate,
> | maximum, ticket) VALUES('blabla','" & rate & "','" & maximum & "','" &
> | RadioButtonList1.SelectedValue & "')"
> |
> |
> | SqlDataSource1.Insert()
> |
> |
> | CREATE TABLE Example(
> | userName nvarchar(50),
> | rate decimal(2, 2),
> | maximum decimal(6, 2),
> | ticket nchar(1)
> | )
> ||||I'm not dotnet savvy but you might try something to the effect of;
MsgBox SqlDataSource1.InsertCommand
to see the actual SQL being passed.
--
Regards,
Dave Patrick ...Please no email replies - reply in newsgroup.
Microsoft Certified Professional
Microsoft MVP [Windows]
http://www.microsoft.com/protect
"Dot Net Daddy" wrote:
| Hi,
|
| Already tried that. But this time I got the error:
|
| There are fewer columns in the INSERT statement than values specified
| in the VALUES clause. The number of values in the VALUES clause must
| match the number of columns specified in the INSERT statement.|||thank you so much.. that helped..
silly me.. I was passing the logon name to the database, which was
causing the problem..
thanks for your help...
Dot Net Daddy wrote:
> Hi,
> Already tried that. But this time I got the error:
> There are fewer columns in the INSERT statement than values specified
> in the VALUES clause. The number of values in the VALUES clause must
> match the number of columns specified in the INSERT statement.
>
>
> Dave Patrick wrote:
> > Try dropping the string delimiters (single quotes). Something like;
> >
> > "INSERT INTO Example(userName, rate,
> > maximum, ticket) VALUES('blabla'," & rate & "," & maximum & ",'" &
> > RadioButtonList1.SelectedValue & "')"
> >
> > --
> >
> > Regards,
> >
> > Dave Patrick ...Please no email replies - reply in newsgroup.
> > Microsoft Certified Professional
> > Microsoft MVP [Windows]
> > http://www.microsoft.com/protect
> >
> > "Dot Net Daddy" wrote:
> > | Hello,
> > |
> > | I cannot get the following Insert Command work. I get the error:
> > |
> > |
> > | Error converting data type varchar to numeric.
> > | Description: An unhandled exception occurred during the execution of
> > | the current web request. Please review the stack trace for more
> > | information about the error and where it originated in the code.
> > |
> > |
> > | Exception Details: System.Data.SqlClient.SqlException: Error converting
> > |
> > | data type varchar to numeric.
> > |
> > |
> > | However 'rate' and 'maximum' variables are declared as Decimal
> > |
> > |
> > | Dim rate As Decimal
> > | Dim maximumAs Decimal
> > |
> > |
> > | SqlDataSource1.InsertCommand = "INSERT INTO Example(userName, rate,
> > | maximum, ticket) VALUES('blabla','" & rate & "','" & maximum & "','" &
> > | RadioButtonList1.SelectedValue & "')"
> > |
> > |
> > | SqlDataSource1.Insert()
> > |
> > |
> > | CREATE TABLE Example(
> > | userName nvarchar(50),
> > | rate decimal(2, 2),
> > | maximum decimal(6, 2),
> > | ticket nchar(1)
> > | )
> > ||||Good to hear. You're welcome.
--
Regards,
Dave Patrick ...Please no email replies - reply in newsgroup.
Microsoft Certified Professional
Microsoft MVP [Windows]
http://www.microsoft.com/protect
"Dot Net Daddy" wrote:
| thank you so much.. that helped..
|
| silly me.. I was passing the logon name to the database, which was
| causing the problem..
|
| thanks for your help...|||I see you have found a resolution to your immediate problem but I want to
point out that this code has a serious vulnerability to SQL injection. I
strongly recommend that you use command parameters instead of string
concatenation and perhaps also use only stored procedures so that direct
table permissions are not needed.
Google "SQL injection" find many discussions on the topic.
--
Hope this helps.
Dan Guzman
SQL Server MVP
"Dot Net Daddy" <cagriandac@.gmail.com> wrote in message
news:1156041975.673742.64030@.h48g2000cwc.googlegroups.com...
> Hello,
> I cannot get the following Insert Command work. I get the error:
>
> Error converting data type varchar to numeric.
> Description: An unhandled exception occurred during the execution of
> the current web request. Please review the stack trace for more
> information about the error and where it originated in the code.
>
> Exception Details: System.Data.SqlClient.SqlException: Error converting
> data type varchar to numeric.
>
> However 'rate' and 'maximum' variables are declared as Decimal
>
> Dim rate As Decimal
> Dim maximumAs Decimal
>
> SqlDataSource1.InsertCommand = "INSERT INTO Example(userName, rate,
> maximum, ticket) VALUES('blabla','" & rate & "','" & maximum & "','" &
> RadioButtonList1.SelectedValue & "')"
>
> SqlDataSource1.Insert()
>
> CREATE TABLE Example(
> userName nvarchar(50),
> rate decimal(2, 2),
> maximum decimal(6, 2),
> ticket nchar(1)
> )
>

Error converting data type varchar to numeric.

Hello,
I cannot get the following Insert Command work. I get the error:
Error converting data type varchar to numeric.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Error converting
data type varchar to numeric.
However 'rate' and 'maximum' variables are declared as Decimal
Dim rate As Decimal
Dim maximumAs Decimal
SqlDataSource1.InsertCommand = "INSERT INTO Example(userName, rate,
maximum, ticket) VALUES('blabla','" & rate & "','" & maximum & "','" &
RadioButtonList1.SelectedValue & "')"
SqlDataSource1.Insert()
CREATE TABLE Example(
userName nvarchar(50),
rate decimal(2, 2),
maximum decimal(6, 2),
ticket nchar(1)
)Try dropping the string delimiters (single quotes). Something like;
"INSERT INTO Example(userName, rate,
maximum, ticket) VALUES('blabla'," & rate & "," & maximum & ",'" &
RadioButtonList1.SelectedValue & "')"
Regards,
Dave Patrick ...Please no email replies - reply in newsgroup.
Microsoft Certified Professional
Microsoft MVP [Windows]
http://www.microsoft.com/protect
"Dot Net Daddy" wrote:
| Hello,
|
| I cannot get the following Insert Command work. I get the error:
|
|
| Error converting data type varchar to numeric.
| Description: An unhandled exception occurred during the execution of
| the current web request. Please review the stack trace for more
| information about the error and where it originated in the code.
|
|
| Exception Details: System.Data.SqlClient.SqlException: Error converting
|
| data type varchar to numeric.
|
|
| However 'rate' and 'maximum' variables are declared as Decimal
|
|
| Dim rate As Decimal
| Dim maximumAs Decimal
|
|
| SqlDataSource1.InsertCommand = "INSERT INTO Example(userName, rate,
| maximum, ticket) VALUES('blabla','" & rate & "','" & maximum & "','" &
| RadioButtonList1.SelectedValue & "')"
|
|
| SqlDataSource1.Insert()
|
|
| CREATE TABLE Example(
| userName nvarchar(50),
| rate decimal(2, 2),
| maximum decimal(6, 2),
| ticket nchar(1)
| )
||||Hi,
Already tried that. But this time I got the error:
There are fewer columns in the INSERT statement than values specified
in the VALUES clause. The number of values in the VALUES clause must
match the number of columns specified in the INSERT statement.
Dave Patrick wrote:
> Try dropping the string delimiters (single quotes). Something like;
> "INSERT INTO Example(userName, rate,
> maximum, ticket) VALUES('blabla'," & rate & "," & maximum & ",'" &
> RadioButtonList1.SelectedValue & "')"
> --
> Regards,
> Dave Patrick ...Please no email replies - reply in newsgroup.
> Microsoft Certified Professional
> Microsoft MVP [Windows]
> http://www.microsoft.com/protect
> "Dot Net Daddy" wrote:
> | Hello,
> |
> | I cannot get the following Insert Command work. I get the error:
> |
> |
> | Error converting data type varchar to numeric.
> | Description: An unhandled exception occurred during the execution of
> | the current web request. Please review the stack trace for more
> | information about the error and where it originated in the code.
> |
> |
> | Exception Details: System.Data.SqlClient.SqlException: Error converting
> |
> | data type varchar to numeric.
> |
> |
> | However 'rate' and 'maximum' variables are declared as Decimal
> |
> |
> | Dim rate As Decimal
> | Dim maximumAs Decimal
> |
> |
> | SqlDataSource1.InsertCommand = "INSERT INTO Example(userName, rate,
> | maximum, ticket) VALUES('blabla','" & rate & "','" & maximum & "','" &
> | RadioButtonList1.SelectedValue & "')"
> |
> |
> | SqlDataSource1.Insert()
> |
> |
> | CREATE TABLE Example(
> | userName nvarchar(50),
> | rate decimal(2, 2),
> | maximum decimal(6, 2),
> | ticket nchar(1)
> | )
> ||||I'm not dotnet savvy but you might try something to the effect of;
MsgBox SqlDataSource1.InsertCommand
to see the actual SQL being passed.
Regards,
Dave Patrick ...Please no email replies - reply in newsgroup.
Microsoft Certified Professional
Microsoft MVP [Windows]
http://www.microsoft.com/protect
"Dot Net Daddy" wrote:
| Hi,
|
| Already tried that. But this time I got the error:
|
| There are fewer columns in the INSERT statement than values specified
| in the VALUES clause. The number of values in the VALUES clause must
| match the number of columns specified in the INSERT statement.|||thank you so much.. that helped..
silly me.. I was passing the logon name to the database, which was
causing the problem..
thanks for your help...
Dot Net Daddy wrote:[vbcol=seagreen]
> Hi,
> Already tried that. But this time I got the error:
> There are fewer columns in the INSERT statement than values specified
> in the VALUES clause. The number of values in the VALUES clause must
> match the number of columns specified in the INSERT statement.
>
>
> Dave Patrick wrote:|||Good to hear. You're welcome.
Regards,
Dave Patrick ...Please no email replies - reply in newsgroup.
Microsoft Certified Professional
Microsoft MVP [Windows]
http://www.microsoft.com/protect
"Dot Net Daddy" wrote:
| thank you so much.. that helped..
|
| silly me.. I was passing the logon name to the database, which was
| causing the problem..
|
| thanks for your help...|||I see you have found a resolution to your immediate problem but I want to
point out that this code has a serious vulnerability to SQL injection. I
strongly recommend that you use command parameters instead of string
concatenation and perhaps also use only stored procedures so that direct
table permissions are not needed.
Google "SQL injection" find many discussions on the topic.
Hope this helps.
Dan Guzman
SQL Server MVP
"Dot Net Daddy" <cagriandac@.gmail.com> wrote in message
news:1156041975.673742.64030@.h48g2000cwc.googlegroups.com...
> Hello,
> I cannot get the following Insert Command work. I get the error:
>
> Error converting data type varchar to numeric.
> Description: An unhandled exception occurred during the execution of
> the current web request. Please review the stack trace for more
> information about the error and where it originated in the code.
>
> Exception Details: System.Data.SqlClient.SqlException: Error converting
> data type varchar to numeric.
>
> However 'rate' and 'maximum' variables are declared as Decimal
>
> Dim rate As Decimal
> Dim maximumAs Decimal
>
> SqlDataSource1.InsertCommand = "INSERT INTO Example(userName, rate,
> maximum, ticket) VALUES('blabla','" & rate & "','" & maximum & "','" &
> RadioButtonList1.SelectedValue & "')"
>
> SqlDataSource1.Insert()
>
> CREATE TABLE Example(
> userName nvarchar(50),
> rate decimal(2, 2),
> maximum decimal(6, 2),
> ticket nchar(1)
> )
>

Error converting data type varchar to numeric.

Excuse me for my english.
Let us start with the base. I work with SQLServer 2000. My table has 12
columns of the type varchar Ex.:(Condition1_Min, Condition1_Max,
Condition2_Min, Condition2_Max etc...)
There are values which must be interpreted like the numerical one and of
other as alpha. Here a request which does not function in Query Analyser
It seems that if I cast my condition1_min, for example, as soon as I have a
request which still uses condition1_min but not cast then sql server this
error message gives me.
Here an example of request:
SELECT
NO_MACHINE,NOM_PROCEDURE,CONDITION1_MIN,
CONDITION1_MAX,CONDITION1_TOUS,CONDI
TION2_MIN,CONDITION2_MAX,CONDITION2_TOUS
,CONDITION3_MIN,CONDITION3_MAX,CONDI
TION3_TOUS,CONDITION4_MIN,CONDITION4_MAX
,CONDITION4_TOUS,CONDITION5_MIN,COND
ITION5_MAX,CONDITION5_TOUS,
CONDITION6_MIN,CONDITION6_MAX,CONDITION6
_TOUS,NO_GRP_INSTRUCTIONS,RAZ_BORNE
FROM MES_PROCEDURECONDITIONS
WHERE (NO_MACHINE = '00300') AND (CONDITION1_MIN >= 'AK' AND CONDITION1_MAX
<= 'AK') AND (CONDITION2_MIN >= '4' AND CONDITION2_MAX <= '4') AND
NOM_PROCEDURE = 'ChangRouleaux' OR (NO_MACHINE = '00300') AND
(CONDITION1_MIN >= '2' AND CONDITION1_MAX <= '2') AND (CONDITION2_MIN >= '4
'
AND CONDITION2_MAX <= '4') AND NOM_PROCEDURE = 'Insp. Feuille Début' OR
(NO_MACHINE = '00300') AND (CONDITION1_MIN >= 'False' AND CONDITION1_MAX <=
'False') AND (cast(CONDITION2_MIN as decimal) >= 0.065 AND
cast(CONDITION2_MAX as decimal) <= 0.065) AND (CONDITION3_MIN >= '4' AND
CONDITION3_MAX <= '4') AND (CONDITION4_MIN >= '2' AND CONDITION4_MAX <= '2'
)
AND NOM_PROCEDURE = 'Inspection Final' OR (NO_MACHINE = '00300') AND
(CONDITION1_MIN >= 'LR' AND CONDITION1_MAX <= 'LR') AND (CONDITION2_MIN >=
'2' AND CONDITION2_MAX <= '2') AND (CONDITION3_MIN >= '4' AND CONDITION3_MA
X
<= '4') AND (CONDITION4_MIN >= '0' AND CONDITION4_MAX <= '0') AND
NOM_PROCEDURE = 'Largeur 1 re bob équ' OR (NO_MACHINE = '00300') AND
(CONDITION1_MIN >= 'False' AND CONDITION1_MAX <= 'False') AND
(CONDITION2_MIN >= 'LR' AND CONDITION2_MAX <= 'LR') AND (CONDITION3_MIN >=
'0' AND CONDITION3_MAX <= '0') AND (CONDITION4_MIN >= '4' AND CONDITION4_MA
X
<= '4') AND NOM_PROCEDURE = 'Largeur Final 1er bob' OR (NO_MACHINE =
'00300') AND (CONDITION1_MIN >= 'AK' AND CONDITION1_MAX <= 'AK') AND
(CONDITION2_MIN >= 'LR' AND CONDITION2_MAX <= 'LR') AND (CONDITION3_MIN >=
'0' AND CONDITION3_MAX <= '0') AND (CONDITION4_MIN >= '4' AND CONDITION4_MA
X
<= '4') AND NOM_PROCEDURE = 'Largeur Foil 1re bobi.' OR (NO_MACHINE =
'00300') AND (CONDITION1_MIN >= 'LR' AND CONDITION1_MAX <= 'LR') AND
(CONDITION2_MIN >= '4' AND CONDITION2_MAX <= '4') AND NOM_PROCEDURE =
'Largeur_PI' OR (NO_MACHINE = '00300') AND (CONDITION1_MIN >= '145418001'
AND CONDITION1_MAX <= '145418001') AND (CONDITION2_MIN >= '2' AND
CONDITION2_MAX <= '2') AND (CONDITION3_MIN >= '875' AND CONDITION3_MAX <=
'875') AND (CONDITION4_MIN >= '4' AND CONDITION4_MAX <= '4') AND
NOM_PROCEDURE = 'Lavage' OR (NO_MACHINE = '00300') AND (CONDITION1_MIN <=
'False' AND CONDITION1_MAX >= 'False') AND (cast(CONDITION2_MIN as decimal)
>= 0.065 AND cast(CONDITION2_MAX as decimal(38,10)) <= 0.065) AND
(CONDITION3_MIN >= '4' AND CONDITION3_MAX <= '4') AND NOM_PROCEDURE =
'Standardi. Final 1er b' OR (NO_MACHINE = '00300') AND (cast(CONDITION1_MI
N
as decimal(38,10)) >= 0.065 AND cast(CONDITION1_MAX as decimal) <= 0.065) AN
D
(CONDITION2_MIN >= '2' AND CONDITION2_MAX <= '2') AND (CONDITION3_MIN >=
'4' AND CONDITION3_MAX <= '4') AND NOM_PROCEDURE = 'Standardisation Déb.'
ORDER BY NO_MACHINE,NOM_PROCEDURE
Under condition min and max I can have alphas and num data. The request is
made with generic program. I need your ideas.
Thank you for your assistance!!!Hi
Posting DDL and example data as described in
http://www.aspfaq.com/etiquett___e.asp?id=5006 helps when answering quest
ions
like this.
CONDITION2_MIN >= '4' AND CONDITION2_MAX <= '4'
is not the same as
CONDITION2_MIN >= 4 AND CONDITION2_MAX <= 4
e.g.
SELECT * FROM
( SELECT '10' as [Min], '20' AS [MAX]
UNION ALL SELECT '4', '8' ) A
WHERE [Min] >= '4'
SELECT * FROM
( SELECT '10' as [Min], '20' AS [MAX]
UNION ALL SELECT '4', '8' ) A
WHERE [Min] >= 4
And it would seem more logical if the condition was
CONDITION2_MIN <= 4 AND CONDITION2_MAX >= 4
If you are having conversion errors using PATINDEX or ISNUMERIC may help.
John
"Ric" wrote:

> Excuse me for my english.
> Let us start with the base. I work with SQLServer 2000. My table has 12
> columns of the type varchar Ex.:(Condition1_Min, Condition1_Max,
> Condition2_Min, Condition2_Max etc...)
> There are values which must be interpreted like the numerical one and of
> other as alpha. Here a request which does not function in Query Analyser
> It seems that if I cast my condition1_min, for example, as soon as I have
a
> request which still uses condition1_min but not cast then sql server this
> error message gives me.
> Here an example of request:
> SELECT
> NO_MACHINE,NOM_PROCEDURE,CONDITION1_MIN,
CONDITION1_MAX,CONDITION1_TOUS,CONDITION
2_
MIN,CONDITION2_MAX,CONDITION2_TOUS,CONDI
TION3_MIN,CONDITION3_MAX,CONDITION3_TOUS
,CON
DITION4_MIN,CONDITION4_MAX,CONDITION4_TO
US,CONDITION5_MIN,CONDITION5_MAX,CONDITI
ON5_
TOU
S,CONDITION6_MIN,CONDITION6_MAX,CONDITIO
N6_TOUS,NO_GRP_INSTRUCTIONS,RAZ_BORNE[co
lor=darkred
]
> FROM MES_PROCEDURECONDITIONS
> WHERE (NO_MACHINE = '00300') AND (CONDITION1_MIN >= 'AK' AND CONDITION1_MA
X
> <= 'AK') AND (CONDITION2_MIN >= '4' AND CONDITION2_MAX <= '4') AND
> NOM_PROCEDURE = 'ChangRouleaux' OR (NO_MACHINE = '00300') AND
> (CONDITION1_MIN >= '2' AND CONDITION1_MAX <= '2') AND (CONDITION2_MIN >=
'4'
> AND CONDITION2_MAX <= '4') AND NOM_PROCEDURE = 'Insp. Feuille Début' OR
> (NO_MACHINE = '00300') AND (CONDITION1_MIN >= 'False' AND CONDITION1_MAX
<=
> 'False') AND (cast(CONDITION2_MIN as decimal) >= 0.065 AND
> cast(CONDITION2_MAX as decimal) <= 0.065) AND (CONDITION3_MIN >= '4' AND
> CONDITION3_MAX <= '4') AND (CONDITION4_MIN >= '2' AND CONDITION4_MAX <= '
2')
> AND NOM_PROCEDURE = 'Inspection Final' OR (NO_MACHINE = '00300') AND
> (CONDITION1_MIN >= 'LR' AND CONDITION1_MAX <= 'LR') AND (CONDITION2_MIN >
=
> '2' AND CONDITION2_MAX <= '2') AND (CONDITION3_MIN >= '4' AND CONDITION3_
MAX
> <= '4') AND (CONDITION4_MIN >= '0' AND CONDITION4_MAX <= '0') AND
> NOM_PROCEDURE = 'Largeur 1 re bob équ' OR (NO_MACHINE = '00300') AND
> (CONDITION1_MIN >= 'False' AND CONDITION1_MAX <= 'False') AND
> (CONDITION2_MIN >= 'LR' AND CONDITION2_MAX <= 'LR') AND (CONDITION3_MIN >
=
> '0' AND CONDITION3_MAX <= '0') AND (CONDITION4_MIN >= '4' AND CONDITION4_
MAX
> <= '4') AND NOM_PROCEDURE = 'Largeur Final 1er bob' OR (NO_MACHINE =
> '00300') AND (CONDITION1_MIN >= 'AK' AND CONDITION1_MAX <= 'AK') AND
> (CONDITION2_MIN >= 'LR' AND CONDITION2_MAX <= 'LR') AND (CONDITION3_MIN >
=
> '0' AND CONDITION3_MAX <= '0') AND (CONDITION4_MIN >= '4' AND CONDITION4_
MAX
> <= '4') AND NOM_PROCEDURE = 'Largeur Foil 1re bobi.' OR (NO_MACHINE =
> '00300') AND (CONDITION1_MIN >= 'LR' AND CONDITION1_MAX <= 'LR') AND
> (CONDITION2_MIN >= '4' AND CONDITION2_MAX <= '4') AND NOM_PROCEDURE =
> 'Largeur_PI' OR (NO_MACHINE = '00300') AND (CONDITION1_MIN >= '145418001
'
> AND CONDITION1_MAX <= '145418001') AND (CONDITION2_MIN >= '2' AND
> CONDITION2_MAX <= '2') AND (CONDITION3_MIN >= '875' AND CONDITION3_MAX <=
> '875') AND (CONDITION4_MIN >= '4' AND CONDITION4_MAX <= '4') AND
> NOM_PROCEDURE = 'Lavage' OR (NO_MACHINE = '00300') AND (CONDITION1_MIN <
=
> 'False' AND CONDITION1_MAX >= 'False') AND (cast(CONDITION2_MIN as decima
l)
> (CONDITION3_MIN >= '4' AND CONDITION3_MAX <= '4') AND NOM_PROCEDURE =
> 'Standardi. Final 1er b' OR (NO_MACHINE = '00300') AND (cast(CONDITION1_
MIN
> as decimal(38,10)) >= 0.065 AND cast(CONDITION1_MAX as decimal) <= 0.065)
AND
> (CONDITION2_MIN >= '2' AND CONDITION2_MAX <= '2') AND (CONDITION3_MIN >=
> '4' AND CONDITION3_MAX <= '4') AND NOM_PROCEDURE = 'Standardisation Déb.'
> ORDER BY NO_MACHINE,NOM_PROCEDURE
> Under condition min and max I can have alphas and num data. The request is
> made with generic program. I need your ideas.
> Thank you for your assistance!!!
>[/color]

Error converting data type varchar to numeric

Hi,

Thank you in advance for your comments/suggestions. I am trying to create a View of a Table. The table is created by another application so I am unable to recreate it they way I want, also the data that is in the columns that I want to CAST are "numbers" not letters and will only be numbers. In the view I need certain columns to be CAST as numeric from varchar.

Here is the syntax that I am currently using:

Code Snippet

SELECT CAST(szF1 AS datetime) AS [Login Date/Time], szF2 AS [User Name], CAST(szF3 AS numeric) AS [Documents Indexed], CAST(szF4 AS datetime) AS [Logout Date/Time], CAST(szF5 AS numeric) AS [Documents Sent to QC], CAST(szF6 AS numeric) AS [Documents Reconciled], szF7 AS [Reject Reason], CAST(szF8 AS datetime) AS [Report Date]

FROM dbo.F_Report_Data AS a

WHERE (szF3 <> 'Blank')

When I open the view I get the error message about converting varchar to numeric.

Thanks,

Erik

Try running this query:

Code Snippet

SELECT CAST(szF1 AS datetime) AS [Login Date/Time],
szF2 AS [User Name],
-- CAST(szF3 AS numeric) AS [Documents Indexed],
szF3,
CAST(szF4 AS datetime) AS [Logout Date/Time],
-- CAST(szF5 AS numeric) AS [Documents Sent to QC],
-- CAST(szF6 AS numeric) AS [Documents Reconciled],
szF5,
szF6,
szF7 AS [Reject Reason],
CAST(szF8 AS datetime) AS [Report Date]
FROM dbo.F_Report_Data AS a
where isNumeric (szF3 + 'D0') = 0
or isNumeric (szF5 + 'D0') = 0
or isNumeric (szF6 + 'D0') = 0

And post any results that get returned.|||

I tried your suggestion and I got an error: "Error in list of function arguments: '=' not recognized. Unable to parse query text.

|||

It's likely because you have data in the szF5 or szF6 columns that can't be converted to numeric. For example, if I had the value aaa in szF5, I would get that error. More common is if I have a zero length string in the column, that can't be converted to numeric and I would get the error. A null would be fine but a zero length string would cause the error.

-Sue

|||

I would suggest (1) give the schema of the table and (2) give 5 sample rows of data from the table by doing a

select top 5 * from F_Report_Data

|||

The 3 columns that I want to cast as numeric have only numbers in them.

1/24/2007 9:58:03 AM admin 207 1/24/2007 2:08:55 PM 0 0 1/24/2007 12:00:00 AM
1/24/2007 9:59:03 AM admin 0 1/24/2007 4:09:25 PM 1 0 Unable to read case number 1/24/2007 12:00:00 AM
1/24/2007 9:56:03 AM admin 0 1/24/2007 4:26:33 PM 0 3 1/24/2007 12:00:00 AM
1/25/2007 1:55:19 PM admin 0 1/25/2007 3:32:51 PM 0 0 1/25/2007 12:00:00 AM
1/25/2007 1:55:19 PM test 0 1/25/2007 4:11:09 PM 1 0 Unable to read case number 1/25/2007 12:00:00 AM

The items in bold are thecolumns that I am trying to covnert/cast as numeric.

|||

The 3 columns that I want to cast as numeric have only numbers in them.

Code Snippet

1/24/2007 9:58:03 AM admin 207 1/24/2007 2:08:55 PM 0 0 1/24/2007 12:00:00 AM
1/24/2007 9:59:03 AM admin 0 1/24/2007 4:09:25 PM 1 0 Unable to read case number 1/24/2007 12:00:00 AM
1/24/2007 9:56:03 AM admin 0 1/24/2007 4:26:33 PM 0 3 1/24/2007 12:00:00 AM
1/25/2007 1:55:19 PM admin 0 1/25/2007 3:32:51 PM 0 0 1/25/2007 12:00:00 AM
1/25/2007 1:55:19 PM test 0 1/25/2007 4:11:09 PM 1 0 Unable to read case number 1/25/2007 12:00:00 AM

The items in bold are thecolumns that I am trying to covnert/cast as numeric.

Could you clarify by what you mean "Schema", it has been a while since my DB class and I am not a DBA. Every column is varchar(8000),null except for the PK which is (int, not null).

I awm giong to attempt to see if I can get the necessary results w/o convert/cast because there is supposed to be implicit conversion of varchar to numeric.

|||

Actually, you have answered the schema question -- all columns are varchar(8000) except for the PK which is integer -- a "wow" table. That should be enough for now. Try running this query and see if any results are returned:

Code Snippet

select left(szF1, 25) as szF1,
left(szF2, 25) as szF2,
left(szF3, 25) as szF3,
left(szF4, 25) as szF4,
left(szF5, 25) as szF5,
left(szF6, 25) as szF6,
left(szF7, 25) as szF7,
left(szF8, 25) as szF8
from dbo.F_Report_data
where isDate(szF1) = 0
or isNumeric (szF3 + 'D0') = 0
or isDate(szF4) = 0
or isNumeric (szF5 + 'D0') = 0
or isNumeric (szF6 + 'D0') = 0
or isDate(szF8) = 0

|||

Yes it returned a result, it's good that it returned a result but does that mean that we can/cannot convert/cast a varchar as a numeric? Thanks for your help!!

|||

Please post a sampling of the results that you received. It means that you will might either need to change the table or modify the way you display the data so that it is properly "clensed" -- you have dirty data.

|||

Here are the results:

Code Snippet

01/24/2007 09:58:03 AM admin 207 01/24/2007 02:08:55 PM 0 0 20070124
01/24/2007 09:59:03 AM admin 0 01/24/2007 04:09:25 PM 1 0 Unable to read case numbe 20070124
01/24/2007 09:56:03 AM admin 0 01/24/2007 04:26:33 PM 0 3 20070124
01/25/2007 01:55:19 PM admin 3 01/25/2007 03:32:51 PM 0 0 20070125

01/25/2007 01:55:19 PM test 0 01/25/2007 04:11:09 PM 1 0 Unable to read case numbe 20070125

| szf1| |szF2| szF3 |--szF4-| szF5 sz F6 |-szF7-| |szF8|

I just noticed that the query trimmed szF7 (Where it says "Unable to read case numbe"), I will need that field a little larger for the text. I never would have thought that there would be so much trouble to convert/cast a varchar to a numeric in a view.|||That did not display the same way it did on my screen when I was typing it. I hope it isn't too confusing.|||

Can somebody point Erik to an article about cleaning up data? My tests weren't strong enough and I really am not interested in wasting Erik's time. I suspect that blanks in his data caused the isNumeric tests to fail.

Erik:

You can try this query; it will exhibit which test is failing:

Code Snippet

select isDate(rtrim(szF1)) as szF1isDate,
isNumeric (rtrim(szF3) + 'D0') as szF3IsNumeric,
isDate(rtrim(szF4)) as szF4IsDate,
isNumeric (rtrim(szF5) + 'D0') as szF5IsNumeric,
isNumeric (rtrim(szF6) + 'D0') as szF6IsNumeric,
isDate(rtrim(szF8)) as szF8isDate,
left(szF1, 30) as szF1,
left(szF2, 30) as szF2,
left(szF3, 30) as szF3,
left(szF4, 30) as szF4,
left(szF5, 30) as szF5,
left(szF6, 30) as szF6,
left(szF7, 30) as szF7,
left(szF8, 30) as szF8
from dbo.F_Report_data
where isDate(rtrim(szF1)) = 0
or isNumeric (rtrim(szF3) + 'D0') = 0
or isDate(rtrim(szF4)) = 0
or isNumeric (rtrim(szF5) + 'D0') = 0
or isNumeric (rtrim(szF6) + 'D0') = 0
or isDate(rtrim(szF8)) = 0

I feel like I need a fresh set of eyes on this at this point. Help?

|||

Here are the results of the query. I don't really know what they are saying though, could you give me pseudo code explanation of the query?

0,1,0,1,1,0,,Blank,0,,0,0,,
1,1,1,0,0,1,01/25/2007 01:55:19 PM,admin,19,01/25/2007 04:11:43 PM,,,,20070125
1,0,1,1,1,1,05/18/2007 08:37:01 AM,ATRAIN28,,05/18/2007 09:58:22 AM,1,0,Invalid case number,20070518
1,0,1,1,1,1,05/18/2007 08:37:01 AM,ATRAIN28,,05/18/2007 10:01:14 AM,0,1,,20070518

|||

Erik:

To me the problem here is that the columns are not sufficiently typed; this is a design problem that should be fixed. If a column is intended to be used as a number it should be typed as numeric. Similarly, if a column is going to be used as a date it should be typed as a datetime column, not as a varchar. Here is the basic response to the records returned from the query:

0,1,0,1,1,0,,Blank,0,,0,0,,
this record failed for 3 reasons:
(1) The szF1 field is not a valid date (it is an empty string)
(2) The szF4 field is not a valid date (it is an empty string)
(3) the szF8 field is not a valid date (it is an empty string)

1,1,1,0,0,1,01/25/2007 01:55:19 PM,admin,19,01/25/2007 04:11:43 PM,,,,20070125
this record faild for two reasons:
(1) The szF5 field is not numeric (it is an empty string)
(2) the szF6 field is not numeric (it is an empty string)

]

1,0,1,1,1,1,05/18/2007 08:37:01 AM,ATRAIN28,,05/18/2007 09:58:22 AM,1,0,Invalid case number,20070518
this record failed because:
(1) The szF3 field is not numeric (it is an empty string)

1,0,1,1,1,1,05/18/2007 08:37:01 AM,ATRAIN28,,05/18/2007 10:01:14 AM,0,1,,20070518
this record failed because:
(1) The szF3 field is not numeric (it is an empty string)

Now, you might be able to use the NULLIF function to get around these problems since all of these are manifest when the column is an EMPTY string. If you are wanting to test for NUMERIC columns you might also want to give a look to this article about problems with the "isNumeric" built-in function:

http://classicasp.aspfaq.com/general/what-is-wrong-with-isnumeric.html

Error converting data type varchar to numeric

Hi,

Thank you in advance for your comments/suggestions. I am trying to create a View of a Table. The table is created by another application so I am unable to recreate it they way I want, also the data that is in the columns that I want to CAST are "numbers" not letters and will only be numbers. In the view I need certain columns to be CAST as numeric from varchar.

Here is the syntax that I am currently using:

Code Snippet

SELECT CAST(szF1 AS datetime) AS [Login Date/Time], szF2 AS [User Name], CAST(szF3 AS numeric) AS [Documents Indexed], CAST(szF4 AS datetime) AS [Logout Date/Time], CAST(szF5 AS numeric) AS [Documents Sent to QC], CAST(szF6 AS numeric) AS [Documents Reconciled], szF7 AS [Reject Reason], CAST(szF8 AS datetime) AS [Report Date]

FROM dbo.F_Report_Data AS a

WHERE (szF3 <> 'Blank')

When I open the view I get the error message about converting varchar to numeric.

Thanks,

Erik

Try running this query:

Code Snippet

SELECT CAST(szF1 AS datetime) AS [Login Date/Time],
szF2 AS [User Name],
-- CAST(szF3 AS numeric) AS [Documents Indexed],
szF3,
CAST(szF4 AS datetime) AS [Logout Date/Time],
-- CAST(szF5 AS numeric) AS [Documents Sent to QC],
-- CAST(szF6 AS numeric) AS [Documents Reconciled],
szF5,
szF6,
szF7 AS [Reject Reason],
CAST(szF8 AS datetime) AS [Report Date]
FROM dbo.F_Report_Data AS a
where isNumeric (szF3 + 'D0') = 0
or isNumeric (szF5 + 'D0') = 0
or isNumeric (szF6 + 'D0') = 0

And post any results that get returned.|||

I tried your suggestion and I got an error: "Error in list of function arguments: '=' not recognized. Unable to parse query text.

|||

It's likely because you have data in the szF5 or szF6 columns that can't be converted to numeric. For example, if I had the value aaa in szF5, I would get that error. More common is if I have a zero length string in the column, that can't be converted to numeric and I would get the error. A null would be fine but a zero length string would cause the error.

-Sue

|||

I would suggest (1) give the schema of the table and (2) give 5 sample rows of data from the table by doing a

select top 5 * from F_Report_Data

|||

The 3 columns that I want to cast as numeric have only numbers in them.

1/24/2007 9:58:03 AM admin 207 1/24/2007 2:08:55 PM 0 0 1/24/2007 12:00:00 AM
1/24/2007 9:59:03 AM admin 0 1/24/2007 4:09:25 PM 1 0 Unable to read case number 1/24/2007 12:00:00 AM
1/24/2007 9:56:03 AM admin 0 1/24/2007 4:26:33 PM 0 3 1/24/2007 12:00:00 AM
1/25/2007 1:55:19 PM admin 0 1/25/2007 3:32:51 PM 0 0 1/25/2007 12:00:00 AM
1/25/2007 1:55:19 PM test 0 1/25/2007 4:11:09 PM 1 0 Unable to read case number 1/25/2007 12:00:00 AM

The items in bold are thecolumns that I am trying to covnert/cast as numeric.

|||

The 3 columns that I want to cast as numeric have only numbers in them.

Code Snippet

1/24/2007 9:58:03 AM admin 207 1/24/2007 2:08:55 PM 0 0 1/24/2007 12:00:00 AM
1/24/2007 9:59:03 AM admin 0 1/24/2007 4:09:25 PM 1 0 Unable to read case number 1/24/2007 12:00:00 AM
1/24/2007 9:56:03 AM admin 0 1/24/2007 4:26:33 PM 0 3 1/24/2007 12:00:00 AM
1/25/2007 1:55:19 PM admin 0 1/25/2007 3:32:51 PM 0 0 1/25/2007 12:00:00 AM
1/25/2007 1:55:19 PM test 0 1/25/2007 4:11:09 PM 1 0 Unable to read case number 1/25/2007 12:00:00 AM

The items in bold are thecolumns that I am trying to covnert/cast as numeric.

Could you clarify by what you mean "Schema", it has been a while since my DB class and I am not a DBA. Every column is varchar(8000),null except for the PK which is (int, not null).

I awm giong to attempt to see if I can get the necessary results w/o convert/cast because there is supposed to be implicit conversion of varchar to numeric.

|||

Actually, you have answered the schema question -- all columns are varchar(8000) except for the PK which is integer -- a "wow" table. That should be enough for now. Try running this query and see if any results are returned:

Code Snippet

select left(szF1, 25) as szF1,
left(szF2, 25) as szF2,
left(szF3, 25) as szF3,
left(szF4, 25) as szF4,
left(szF5, 25) as szF5,
left(szF6, 25) as szF6,
left(szF7, 25) as szF7,
left(szF8, 25) as szF8
from dbo.F_Report_data
where isDate(szF1) = 0
or isNumeric (szF3 + 'D0') = 0
or isDate(szF4) = 0
or isNumeric (szF5 + 'D0') = 0
or isNumeric (szF6 + 'D0') = 0
or isDate(szF8) = 0

|||

Yes it returned a result, it's good that it returned a result but does that mean that we can/cannot convert/cast a varchar as a numeric? Thanks for your help!!

|||

Please post a sampling of the results that you received. It means that you will might either need to change the table or modify the way you display the data so that it is properly "clensed" -- you have dirty data.

|||

Here are the results:

Code Snippet

01/24/2007 09:58:03 AM admin 207 01/24/2007 02:08:55 PM 0 0 20070124
01/24/2007 09:59:03 AM admin 0 01/24/2007 04:09:25 PM 1 0 Unable to read case numbe 20070124
01/24/2007 09:56:03 AM admin 0 01/24/2007 04:26:33 PM 0 3 20070124
01/25/2007 01:55:19 PM admin 3 01/25/2007 03:32:51 PM 0 0 20070125

01/25/2007 01:55:19 PM test 0 01/25/2007 04:11:09 PM 1 0 Unable to read case numbe 20070125

| szf1| |szF2| szF3 |--szF4-| szF5 sz F6 |-szF7-| |szF8|

I just noticed that the query trimmed szF7 (Where it says "Unable to read case numbe"), I will need that field a little larger for the text. I never would have thought that there would be so much trouble to convert/cast a varchar to a numeric in a view.|||That did not display the same way it did on my screen when I was typing it. I hope it isn't too confusing.|||

Can somebody point Erik to an article about cleaning up data? My tests weren't strong enough and I really am not interested in wasting Erik's time. I suspect that blanks in his data caused the isNumeric tests to fail.

Erik:

You can try this query; it will exhibit which test is failing:

Code Snippet

select isDate(rtrim(szF1)) as szF1isDate,
isNumeric (rtrim(szF3) + 'D0') as szF3IsNumeric,
isDate(rtrim(szF4)) as szF4IsDate,
isNumeric (rtrim(szF5) + 'D0') as szF5IsNumeric,
isNumeric (rtrim(szF6) + 'D0') as szF6IsNumeric,
isDate(rtrim(szF8)) as szF8isDate,
left(szF1, 30) as szF1,
left(szF2, 30) as szF2,
left(szF3, 30) as szF3,
left(szF4, 30) as szF4,
left(szF5, 30) as szF5,
left(szF6, 30) as szF6,
left(szF7, 30) as szF7,
left(szF8, 30) as szF8
from dbo.F_Report_data
where isDate(rtrim(szF1)) = 0
or isNumeric (rtrim(szF3) + 'D0') = 0
or isDate(rtrim(szF4)) = 0
or isNumeric (rtrim(szF5) + 'D0') = 0
or isNumeric (rtrim(szF6) + 'D0') = 0
or isDate(rtrim(szF8)) = 0

I feel like I need a fresh set of eyes on this at this point. Help?

|||

Here are the results of the query. I don't really know what they are saying though, could you give me pseudo code explanation of the query?

0,1,0,1,1,0,,Blank,0,,0,0,,
1,1,1,0,0,1,01/25/2007 01:55:19 PM,admin,19,01/25/2007 04:11:43 PM,,,,20070125
1,0,1,1,1,1,05/18/2007 08:37:01 AM,ATRAIN28,,05/18/2007 09:58:22 AM,1,0,Invalid case number,20070518
1,0,1,1,1,1,05/18/2007 08:37:01 AM,ATRAIN28,,05/18/2007 10:01:14 AM,0,1,,20070518

|||

Erik:

To me the problem here is that the columns are not sufficiently typed; this is a design problem that should be fixed. If a column is intended to be used as a number it should be typed as numeric. Similarly, if a column is going to be used as a date it should be typed as a datetime column, not as a varchar. Here is the basic response to the records returned from the query:

0,1,0,1,1,0,,Blank,0,,0,0,,
this record failed for 3 reasons:
(1) The szF1 field is not a valid date (it is an empty string)
(2) The szF4 field is not a valid date (it is an empty string)
(3) the szF8 field is not a valid date (it is an empty string)

1,1,1,0,0,1,01/25/2007 01:55:19 PM,admin,19,01/25/2007 04:11:43 PM,,,,20070125
this record faild for two reasons:
(1) The szF5 field is not numeric (it is an empty string)
(2) the szF6 field is not numeric (it is an empty string)

]

1,0,1,1,1,1,05/18/2007 08:37:01 AM,ATRAIN28,,05/18/2007 09:58:22 AM,1,0,Invalid case number,20070518
this record failed because:
(1) The szF3 field is not numeric (it is an empty string)

1,0,1,1,1,1,05/18/2007 08:37:01 AM,ATRAIN28,,05/18/2007 10:01:14 AM,0,1,,20070518
this record failed because:
(1) The szF3 field is not numeric (it is an empty string)

Now, you might be able to use the NULLIF function to get around these problems since all of these are manifest when the column is an EMPTY string. If you are wanting to test for NUMERIC columns you might also want to give a look to this article about problems with the "isNumeric" built-in function:

http://classicasp.aspfaq.com/general/what-is-wrong-with-isnumeric.html

Error converting data type varchar to numeric

Hi,

Thank you in advance for your comments/suggestions. I am trying to create a View of a Table. The table is created by another application so I am unable to recreate it they way I want, also the data that is in the columns that I want to CAST are "numbers" not letters and will only be numbers. In the view I need certain columns to be CAST as numeric from varchar.

Here is the syntax that I am currently using:

Code Snippet

SELECT CAST(szF1 AS datetime) AS [Login Date/Time], szF2 AS [User Name], CAST(szF3 AS numeric) AS [Documents Indexed], CAST(szF4 AS datetime) AS [Logout Date/Time], CAST(szF5 AS numeric) AS [Documents Sent to QC], CAST(szF6 AS numeric) AS [Documents Reconciled], szF7 AS [Reject Reason], CAST(szF8 AS datetime) AS [Report Date]

FROM dbo.F_Report_Data AS a

WHERE (szF3 <> 'Blank')

When I open the view I get the error message about converting varchar to numeric.

Thanks,

Erik

Try running this query:

Code Snippet

SELECT CAST(szF1 AS datetime) AS [Login Date/Time],
szF2 AS [User Name],
-- CAST(szF3 AS numeric) AS [Documents Indexed],
szF3,
CAST(szF4 AS datetime) AS [Logout Date/Time],
-- CAST(szF5 AS numeric) AS [Documents Sent to QC],
-- CAST(szF6 AS numeric) AS [Documents Reconciled],
szF5,
szF6,
szF7 AS [Reject Reason],
CAST(szF8 AS datetime) AS [Report Date]
FROM dbo.F_Report_Data AS a
where isNumeric (szF3 + 'D0') = 0
or isNumeric (szF5 + 'D0') = 0
or isNumeric (szF6 + 'D0') = 0

And post any results that get returned.|||

I tried your suggestion and I got an error: "Error in list of function arguments: '=' not recognized. Unable to parse query text.

|||

It's likely because you have data in the szF5 or szF6 columns that can't be converted to numeric. For example, if I had the value aaa in szF5, I would get that error. More common is if I have a zero length string in the column, that can't be converted to numeric and I would get the error. A null would be fine but a zero length string would cause the error.

-Sue

|||

I would suggest (1) give the schema of the table and (2) give 5 sample rows of data from the table by doing a

select top 5 * from F_Report_Data

|||

The 3 columns that I want to cast as numeric have only numbers in them.

1/24/2007 9:58:03 AM admin 207 1/24/2007 2:08:55 PM 0 0 1/24/2007 12:00:00 AM
1/24/2007 9:59:03 AM admin 0 1/24/2007 4:09:25 PM 1 0 Unable to read case number 1/24/2007 12:00:00 AM
1/24/2007 9:56:03 AM admin 0 1/24/2007 4:26:33 PM 0 3 1/24/2007 12:00:00 AM
1/25/2007 1:55:19 PM admin 0 1/25/2007 3:32:51 PM 0 0 1/25/2007 12:00:00 AM
1/25/2007 1:55:19 PM test 0 1/25/2007 4:11:09 PM 1 0 Unable to read case number 1/25/2007 12:00:00 AM

The items in bold are thecolumns that I am trying to covnert/cast as numeric.

|||

The 3 columns that I want to cast as numeric have only numbers in them.

Code Snippet

1/24/2007 9:58:03 AM admin 207 1/24/2007 2:08:55 PM 0 0 1/24/2007 12:00:00 AM
1/24/2007 9:59:03 AM admin 0 1/24/2007 4:09:25 PM 1 0 Unable to read case number 1/24/2007 12:00:00 AM
1/24/2007 9:56:03 AM admin 0 1/24/2007 4:26:33 PM 0 3 1/24/2007 12:00:00 AM
1/25/2007 1:55:19 PM admin 0 1/25/2007 3:32:51 PM 0 0 1/25/2007 12:00:00 AM
1/25/2007 1:55:19 PM test 0 1/25/2007 4:11:09 PM 1 0 Unable to read case number 1/25/2007 12:00:00 AM

The items in bold are thecolumns that I am trying to covnert/cast as numeric.

Could you clarify by what you mean "Schema", it has been a while since my DB class and I am not a DBA. Every column is varchar(8000),null except for the PK which is (int, not null).

I awm giong to attempt to see if I can get the necessary results w/o convert/cast because there is supposed to be implicit conversion of varchar to numeric.

|||

Actually, you have answered the schema question -- all columns are varchar(8000) except for the PK which is integer -- a "wow" table. That should be enough for now. Try running this query and see if any results are returned:

Code Snippet

select left(szF1, 25) as szF1,
left(szF2, 25) as szF2,
left(szF3, 25) as szF3,
left(szF4, 25) as szF4,
left(szF5, 25) as szF5,
left(szF6, 25) as szF6,
left(szF7, 25) as szF7,
left(szF8, 25) as szF8
from dbo.F_Report_data
where isDate(szF1) = 0
or isNumeric (szF3 + 'D0') = 0
or isDate(szF4) = 0
or isNumeric (szF5 + 'D0') = 0
or isNumeric (szF6 + 'D0') = 0
or isDate(szF8) = 0

|||

Yes it returned a result, it's good that it returned a result but does that mean that we can/cannot convert/cast a varchar as a numeric? Thanks for your help!!

|||

Please post a sampling of the results that you received. It means that you will might either need to change the table or modify the way you display the data so that it is properly "clensed" -- you have dirty data.

|||

Here are the results:

Code Snippet

01/24/2007 09:58:03 AM admin 207 01/24/2007 02:08:55 PM 0 0 20070124
01/24/2007 09:59:03 AM admin 0 01/24/2007 04:09:25 PM 1 0 Unable to read case numbe 20070124
01/24/2007 09:56:03 AM admin 0 01/24/2007 04:26:33 PM 0 3 20070124
01/25/2007 01:55:19 PM admin 3 01/25/2007 03:32:51 PM 0 0 20070125

01/25/2007 01:55:19 PM test 0 01/25/2007 04:11:09 PM 1 0 Unable to read case numbe 20070125

| szf1| |szF2| szF3 |--szF4-| szF5 sz F6 |-szF7-| |szF8|

I just noticed that the query trimmed szF7 (Where it says "Unable to read case numbe"), I will need that field a little larger for the text. I never would have thought that there would be so much trouble to convert/cast a varchar to a numeric in a view.|||That did not display the same way it did on my screen when I was typing it. I hope it isn't too confusing.|||

Can somebody point Erik to an article about cleaning up data? My tests weren't strong enough and I really am not interested in wasting Erik's time. I suspect that blanks in his data caused the isNumeric tests to fail.

Erik:

You can try this query; it will exhibit which test is failing:

Code Snippet

select isDate(rtrim(szF1)) as szF1isDate,
isNumeric (rtrim(szF3) + 'D0') as szF3IsNumeric,
isDate(rtrim(szF4)) as szF4IsDate,
isNumeric (rtrim(szF5) + 'D0') as szF5IsNumeric,
isNumeric (rtrim(szF6) + 'D0') as szF6IsNumeric,
isDate(rtrim(szF8)) as szF8isDate,
left(szF1, 30) as szF1,
left(szF2, 30) as szF2,
left(szF3, 30) as szF3,
left(szF4, 30) as szF4,
left(szF5, 30) as szF5,
left(szF6, 30) as szF6,
left(szF7, 30) as szF7,
left(szF8, 30) as szF8
from dbo.F_Report_data
where isDate(rtrim(szF1)) = 0
or isNumeric (rtrim(szF3) + 'D0') = 0
or isDate(rtrim(szF4)) = 0
or isNumeric (rtrim(szF5) + 'D0') = 0
or isNumeric (rtrim(szF6) + 'D0') = 0
or isDate(rtrim(szF8)) = 0

I feel like I need a fresh set of eyes on this at this point. Help?

|||

Here are the results of the query. I don't really know what they are saying though, could you give me pseudo code explanation of the query?

0,1,0,1,1,0,,Blank,0,,0,0,,
1,1,1,0,0,1,01/25/2007 01:55:19 PM,admin,19,01/25/2007 04:11:43 PM,,,,20070125
1,0,1,1,1,1,05/18/2007 08:37:01 AM,ATRAIN28,,05/18/2007 09:58:22 AM,1,0,Invalid case number,20070518
1,0,1,1,1,1,05/18/2007 08:37:01 AM,ATRAIN28,,05/18/2007 10:01:14 AM,0,1,,20070518

|||

Erik:

To me the problem here is that the columns are not sufficiently typed; this is a design problem that should be fixed. If a column is intended to be used as a number it should be typed as numeric. Similarly, if a column is going to be used as a date it should be typed as a datetime column, not as a varchar. Here is the basic response to the records returned from the query:

0,1,0,1,1,0,,Blank,0,,0,0,,
this record failed for 3 reasons:
(1) The szF1 field is not a valid date (it is an empty string)
(2) The szF4 field is not a valid date (it is an empty string)
(3) the szF8 field is not a valid date (it is an empty string)

1,1,1,0,0,1,01/25/2007 01:55:19 PM,admin,19,01/25/2007 04:11:43 PM,,,,20070125
this record faild for two reasons:
(1) The szF5 field is not numeric (it is an empty string)
(2) the szF6 field is not numeric (it is an empty string)

]

1,0,1,1,1,1,05/18/2007 08:37:01 AM,ATRAIN28,,05/18/2007 09:58:22 AM,1,0,Invalid case number,20070518
this record failed because:
(1) The szF3 field is not numeric (it is an empty string)

1,0,1,1,1,1,05/18/2007 08:37:01 AM,ATRAIN28,,05/18/2007 10:01:14 AM,0,1,,20070518
this record failed because:
(1) The szF3 field is not numeric (it is an empty string)

Now, you might be able to use the NULLIF function to get around these problems since all of these are manifest when the column is an EMPTY string. If you are wanting to test for NUMERIC columns you might also want to give a look to this article about problems with the "isNumeric" built-in function:

http://classicasp.aspfaq.com/general/what-is-wrong-with-isnumeric.html