I have been given a table that is in NVARCHAR format. I cannot change this table. However, I need to get a SUM value. Neither the CAST, nor CONVERT functions work. Can anyone please provide some suggestions?
SELECT SUM(CONVERT(INT, [Product]))
FROM mytable
SELECT SUM(CAST([Product] AS INT))
FROM mytable
Both result in:
Msg 245, Level 16, State 1, Line 300
Conversion failed when converting the nvarchar value 'WP 4.3-CU AB CDE WINDOW ABA5000RSW' to data type int.
'WP 4.3-CU AB CDE WINDOW ABA5000RSW' will NEVER convert to an int.
If 2012+, you can use try_convert(int,[Product])
This will return NULL for the strings which fail the conversion.
Try checking for numeric products?
SELECT
SUM(CONVERT(INT, [Product]))
FROM
mytable
WHERE
ISNUMERIC([Product]) = 1;
Related
When I run this query
CREATE TABLE t
(
tt Geography
)
INSERT INTO t(tt)
SELECT *
FROM OPENQUERY([Server2],'SELECT NULL')
it throws an error
Msg 206, Level 16, State 2, Line 14 Operand type clash: int is
incompatible with geography
But When I run this, it works fine:
INSERT INTO t(tt)
SELECT NULL
I need to use OPENQUERY, how I can fix above problem? Ideally, I need a fix within OPENQUERY
The error is actually telling you the problem here, NULL has a value type of int. This reason for this is because you haven't defined a type for your column, so the default is int and that data type is returned from OPENQUERY. You can see this by running the below:
SELECT system_type_name
FROM sys.dm_exec_describe_first_result_set(N'SELECT NULL;',NULL,0);
Notice value returned is int. You need to hard convert your value:
INSERT INTO t(tt)
SELECT *
FROM OPENQUERY([Server2],'SELECT CONVERT(geography,NULL)');
SELECT AcquistionDate = CONVERT(NVARCHAR,
CASE
WHEN D.CalendarDate NOT IN ('01/01/1900','12/31/9999')
THEN D.CalendarDate
WHEN ac.FirstAccountOpenDate NOT IN ('01/01/1900', '12/31/9999')
THEN ac.FirstAccountOpenDate
END, 126) + 'Z
from TABLE;
I am getting an error
Msg 8114, level 16, state 5, line 1
Error converting data type varchar to bigint
The CONVERT(NVARCHAR....) takes a date and converts it to NVARCHAR in format 126 or yyyy-mm-ddThh:mi:ss.mmm
But then you have +'Z from table I will assume that is a copy paste mistake and that the single quote is not supposed to be there and it is actually + Z from Table in which case I will assume Z is a bigint. Which would mean you are trying to add a NVARCHAR to a BIGINT, which means the NVARCHAR is first tried to be converted to BIGINT which will fail because it is a string representation of a date and not numeric.
The other possibly without knowing more about your code or your DB structure is that one of the date fields in the CASE expression is actually a BIGINT and when you are comparing it to a date representation of a string the conversation fails there.
But I do agree with Chris Berger's comment that this looks like it should be written very differently.
I have a table ConsoleGames wherein all columns are of type varchar(50). When I try to create a new table console_games by amending existing datatypes by using the query:
CREATE TABLE console_games
(
game_rank integer,
game_name varchar(1200),
platform_name varchar(1200),
game_year integer,
genre varchar(200),
publisher varchar(1200),
na_sales float,
eu_sales float,
jp_sales float,
other_sales float
)
INSERT INTO console_games
SELECT *
FROM [dbo].[RAWConsoleGames]
I get the following error message:
Msg 245, Level 16, State 1, Line 17
Conversion failed when converting the varchar value 'SAT' to data type int.
When I look into the data in the table the value 'SAT' is in a column for which I am not changing the datatype. 'SAT' value exists in the Platform column which is of varchar type and I am not trying to change the type to int.
Any help will be appreciated.
Thanks
Clearly 'SAT' is not and will never convert to an INT.
Always best to specify the columns to insert ... things change
Now, if the source data is suspect, add a try_convert(). If the conversion fails, a null value will be returned
I don't know the column names of your source, so I substituted SomeColN
INSERT INTO console_games
SELECT try_convert(integer ,SomeCol1)
,try_convert(varchar(1200),SomeCol2)
,try_convert(varchar(1200),SomeCol3)
,try_convert(integer ,SomeCol4)
,try_convert(varchar(200) ,SomeCol5)
,try_convert(varchar(1200),SomeCol6)
,try_convert(float ,SomeCol7)
,try_convert(float ,SomeCol8)
,try_convert(float ,SomeCol9)
,try_convert(float ,SomeCol10)
FROM [dbo].[RAWConsoleGames]
Just for fun, try:
Select try_convert(int,'SAT')
Select try_convert(int,'25.25')
Select try_convert(int,'25')
You should always define the list of columns you're inserting into, and you should also always define the list of columns you're selecting from. Furthermore, I'd recommend to explicitly do any type conversions instead of leaving that up to SQL Server - if you do it yourself, you know when and what you're doing.
So I'd write that statement like this:
-- **DEFINE** the list of columns you're inserting into
INSERT INTO console_games (rank, name, Platform, year, genre, publisher,
sales, eu_sales, jp_sales, other_sales)
-- **DEFINE** the list of columns you're selecting, and any conversions
SELECT
game_rank, game_name, platform_name,
CAST(game_year AS VARCHAR(50)), genre,
publisher,
CAST(na_sales AS VARCHAR(50)),
CAST(eu_sales AS VARCHAR(50)),
CAST(jp_sales AS VARCHAR(50)),
CAST(other_sales AS VARCHAR(50))
FROM
[dbo].[RAWConsoleGames]
Running some pretty simple SQL here:
select *
from table
where columnA <> convert(int,columnB)
and isnumeric(columnB) = 1
Still getting this error every time:
Conversion failed when converting the nvarchar value 'XXX' to data type int.
If you're using SQL Server 2012 or more recent you could use TRY_PARSE which will return NULL when the parse fails.
SELECT TRY_PARSE('one' as int) -- NULL
, TRY_PARSE('1' as int) -- 1
, TRY_PARSE('0.1' as int) -- NULL
Returns the result of an expression, translated to the requested data type, or null if the cast fails in SQL Server. Use TRY_PARSE only for converting from string to date/time and number types.
Isnumeric has a lot of odd behavior. For example, it also considers currency signs such as $ or £, and even a hyphen (-) to be numeric.
I think you'd be better of using NOT columnB like '%[^0-9]%' to ONLY take numbers into account.
Check the comments at the bottom of the msdn page for isnumeric(), which you can find here: https://msdn.microsoft.com/en-us/library/ms186272.aspx
This may sound weird, but it breaks when do not put the ISNUMERIC check first. Try this out:
WITH [Table]
AS
(
SELECT columnA,columnB
FROM
(
VALUES (1,'2'),
(2,'XXX')
) A(columnA,columnB)
)
select *
from [Table]
where ISNUMERIC(columnB) = 1 --this works
AND columnA <> convert(int,columnB)
--where columnA <> convert(int,columnB) --this doesn't work
-- and isnumeric(columnB) = 1
I suggest you to reverse your checking like this:
SELECT *
FROM table
WHERE CONVERT(NVARCHAR, columnA) <> columnB
I got this using a combination of the answers and comments here. I used a CASE statement in my WHERE clause and also had to use LIKE instead of ISNUMERIC to account for illegal characters. I also had to use BIGINT because a few select samples were overflowing the INT column. Thanks for all of the suggestions everybody!
select * from patient
where PatientExternalID <>
(case when mrn not like '%[^0-9]%'
then convert(bigint, mrn)
else 0
end)
I have a table that looks like this:
id datatype name value
0 nvarchar(255) myName 'Paul'
1 int age '30'
2 float(53) Custom1 0.5
3 float(53) Custom2 1.3
4 float(53) Custom3 2.7
I am wondering if it is possible to do something like the following where I cast the order by as a float - I know this is incorrect syntax but wondering if this can be done.
SELECT datatype, name, value FROM myTable
ORDER BY (float)name
Thanks in advance.
To convert datatypes in SQL you can use CAST or CONVERT:
SELECT CAST('123' AS FLOAT), CONVERT(FLOAT, '123')
But if your name field contains a value that cannot be converted to a valid float, you'll get an error.
e.g.
SELECT CAST('NotAValidFloat' AS FLOAT)
will give you:
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to float.