Conversion failed when converting the varchar value '0%' to data type int - sql

I'm facing a problem with SQL Server.
I've created a table like this:
create table Components
(
pk BIGINT NOT NULL PRIMARY KEY IDENTITY,
id VARCHAR(50),
descr VARCHAR(50),
in_m INT,
in_iy INT,
p_fw VARCHAR(5000)
);
and I'm trying to insert a couple of values:
insert into Components (id, descr, in_m, in_iy, p_fw)
values ('FW000_A', '0%', 0, 0, '[0.0,0.0,0.0]'),
('FW000_B', '1%', 1, 1, '[1.0,1.0,1.0]');
I get the following error:
Msg 245, Level 16, State 1, Line 111
Conversion failed when converting the varchar value '0%' to data type int.
even though the column descr is correctly defined as varchar(50).
Can anybody help me please? Why is SQL Server trying to convert my strings to int values?

What's missing from your question is that you have more than just the two values lines you've shown, and one of the other ones has an integer literal for the descr column, rather than a string.
This example produces the same error:
declare #t table (Descr varchar(50) not null)
insert into #t(Descr) values
('0%'),
(12)
What I believe happens is that SQL Server first tries to determine the data types for all columns in the values clause. Using data type precedence rules, it observes a varchar literal in one row and an int literal in the other, and so determines that the overall type for this column is int and attempts to perform the conversion that leads to the error.
During this process, it does not use any information about the target table into which the values are going to be placed, including the data types of the columns there.

run this and verify the data types;
sp_columns Components
Looks like 'descr' is really an integer

Related

Why I'm getting arithmetic overflow error when inserting bigint number to a bigint column?

I'm trying to insert a number to a column. Column datatype is BIGINT and I'm pretty sure that my number doesn't exceed the max value of BIGINT but still I get
Msg 8115, Level 16, State 2, Line 40
Arithmetic overflow error converting expression to data type int.
The statement has been terminated.
My recent activity was I change the datatype of that column from INT to BIGINT. I think somewhere internally my column is still defined as INT.
Here is my script.
Insert into Customer(Cust_ID)
Select 2150000000
Column Cust_ID datatype is BIGINT in the designer. It is also the PRIMARY_KEY and many table reference it.
EDIT:
Here are some of the migration scripts
DROP TABLE dbo.Customer
GO
EXECUTE sp_rename N'dbo.Tmp_Customer', N'Customer', 'OBJECT'
GO
OK I already found the answer. My table has custom constraints which call scalar functions which requires an INT parameter.
Changing all those function's parameter to BIGINT solves the problem.

Why this simple stored procedure isn't working

Here is the deal, I am receiving an array from C# and I want to insert it into the following table with only 2 columns which are #idUser int and #idRegion int.
The stored procedure needs to receive the array and insert it into the table but somehow it isn't working, it tells me that it cannot convert #idRegion to an int. I tried to use CAST and CONVERT to convert it into int but it isn't working.
The Select From works ok, but not the insert.
Here is the stored procedure (#idUser needs to be the same for all inserted rows):
#idUser int,
#idRegion nvarchar(MAX)
AS
BEGIN
INSERT INTO [UsersRegion] (idUser,IdRegion)
VALUES (#idUser, #idRegion)
SELECT #idUser,cast(value as int) FROM STRING_SPLIT(#idRegion,',')
END
I get this error when running it:
Conversion failed when converting the nvarchar value '1,2,3,4' to data type int.
If you are sending multiple values in #idRegion then when you split them, you may have more than 1 things you need to insert. Therefore, do it like this:
INSERT INTO [UsersRegion] (idUser,IdRegion)
SELECT #idUser, value FROM STRING_SPLIT(#idRegion, ',')
If the target table's IdRegion column is of type int, you need to cast like this:
SELECT #idUser, cast(value as int) FROM STRING_SPLIT(#idRegion, ',')
Above code will insert the same #idUser for every record but a different value for IdRegion depending the splitted items. More on Insert into select from
Your INSERT statement seems to be working with IdRegion while everything else is lowercase id.
However, assuming this is how the actual table column is named and is not a typo...
Your problem is most likely the line that reads:
#idRegion nvarchar(MAX)
Which is declaring the #idRegion variable as a string, while you have stated in the question that it's meant to be an int.
This would explain the casting error.
If you cannot pass it into the procedure as an int from the C# code. Your only other option would be to try to parse it into an int as you have said.

Bulk inserting data gives error

Attempting to bulk insert into a table and I am getting the error:
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 31, column 4 (Birthday).
Below is the code I am trying to use to insert the data:
Bulk Insert Dzt.dbo.Player
From 'A:\New Folder\Seed_Files\Player.csv'
With
(
FieldTerminator=',',
RowTerminator='\n',
FirstRow=2
)
Here is the code I used when making the table:
Use Dzt
Create Table Player
(
Player_ID int,
FirstName varchar(255),
LastName varchar(255),
Birthday date,
Email varchar(255),
L_Flag varchar(255)
);
This is my first attempt at making a table and inserting data so I am thinking it is likely a datatype error for the Birthday field but I have been unable to find anything online that I am able to grasp my head on at this time. I have also tried use the datatype datetime instead of date but I received the same error.
I am using SSMS 2012 to create and insert the data onto a 2012 SQL Server.
Let me know if there is anything else I can provide that might help.
As you suspect it could be a date format error, I would suggest importing the csv into a table with Birthday column set to varchar type. Then use this query to filter the erroneous records.
select birthday from temptable where isdate(birthday) = 0
You could then correct those records and then insert them into your old table.

Why am i getting this error when am creating a table?

I am creating a new table, with various data type, one them in binary(n). When I execute the statement, I end up with the following
Implicit conversion from data type varchar to binary is not allowed, use CONVERT function.
My question: why do I get this error, when there is no data to convert, I am just creating a table?
Create Table EMP.DETAILS
(
ID INT NOT NULL,
TYPE INT,
Created datetime2,
Key_No varchar(5),
Batch_IN INT,
UN_ID BINARY(1) not null default '',
Source INT,
SITE CHAR(1)
)
When I execute the above statement, I get the error mentioned above, But it directs me to the CREATE TABLE line of the code.
The error says "Implicit conversion from data type varchar to binary is not allowed". You are trying to assign a default varchar character to a binary here:
UN_ID BINARY(1) not null default ''
If you absolutely need a default value for a binary column, you can set it directly as something like 0x00:
UN_ID BINARY(1) not null default 0x00
That will basically set your default to 0. You can also set it to an integer value:
UN_ID BINARY(1) not null default 0
And finally, if you absolutely need to to be an empty string, you can find the binary representation of '' with the following SELECT:
SELECT CONVERT(binary, '')
I'm pretty sure it's just 0, though.
Depending on what that column is being used for, though, it might be better suited as a tinyint, char(1), or something similar, rather than a binary(1).

SQL int overflow - insert with encryption

I'm working on implementing encryption in MS SQL 2008R2. Loading data from a CVS file, I have that data in a temp table, and I now want to move some of that data into a encrypted credit card table. However, I keep getting the following error. Code for insert follows, table defs below.
The client ID is below 10 - the number causing the overflow is the very first line of data, CC number.
Error:
Msg 248, Level 16, State 1, Line 4
The conversion of the varchar value '5105105105105100' overflowed an int column.
The statement has been terminated.
Insert statement:
OPEN SYMMETRIC KEY CreditCardKey
DECRYPTION BY CERTIFICATE CreditCardCert;
insert into CreditCard
Select
HASHBYTES('SHA1', t.CreditCard),
EncryptByKey(key_guid('CreditCardKey'), t.CreditCard),
'',
RIGHT(4, t.CreditCard),
'1',
t.Expiration,
convert(int, t.ClientID)
From TempTbl t
TempTbl:
ClientID int.
First, Last, CC, Expiration -- all varchar(50).
All data appears to have imported correctly.
CreditCard: (destination table)
Hash varbinary(200)
Encrypted varbinary(400)
plaintext char(16)
lastfour int
servicecode int
expirationdate Date
ClientID int
Syntax issue was causing the overflow:
My use of the RIGHT function reversed the character and int offset, overflowing the integer expression of the function.
Correct use:
RIGHT ( character_expression , integer_expression )