Reputation: 73
I am getting this error when I am running this query.
I know this is not right but I did, and I just want to am justified answer about it.
Why this error is coming when we are running this below code.
DECLARE @tbl TABLE ( id INT, Name VARCHAR(5) );
INSERT INTO @tbl
SELECT 1 AS Id, 142 AS Alphabets
UNION
SELECT 2, 'XYZ'
UNION
SELECT 2, 'ABC'
SELECT * FROM @tbl
Getting error 'Conversion failed when converting the varchar value to data type int'
Upvotes: 2
Views: 3618
Reputation: 738
In UNION operator : number,order and data type of columns must be same in all queries.
Refer this link for more info : https://msdn.microsoft.com/en-IN/library/ms180026.aspx
Here in your query, data type of 2nd column of 1st select query is different from other union select queries 2nd column.
Thats why you must have got conversion failed error when converting the varchar value to data type int.
Upvotes: 0
Reputation: 969
the problem is 142.
When you write like this 142,
SQL think this union table at second column contain a INT.
you have to write like this '142'
DECLARE @tbl TABLE (id INT, Name VARCHAR(5));
INSERT INTO @tbl
SELECT 1 AS Id, '142' AS Alphabets
UNION
SELECT 2, 'XYZ'
UNION
SELECT 2, 'ABC'
SELECT * FROM @tbl
Upvotes: 2