cdrrr cdrrr - 6 months ago 19
SQL Question

Cast(convert) id to string

I'm trying to display some record from a database based on their ID. In this case, I would like to display the name (column2) based on the ID (column1) when I do a select query and I get this error.


Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric


I understand there's something wrong with converting and I was looking for the answer based on this error, but couldn't find anything. A little help?

The Query what I have tried:

select part1
from primar
where id='1' and id in (select name from primar2)





The data looks like:

ID Name
=== ===
1 Mike
2 John
3 Mary
4 Anne
5 Jack


Later edit: Maybe I explained myself wrong. The
ID
column in the example above belongs to
Table1
and every
ID
have a name associated. In
Table2
there are some other records and among these is the
ID
from
Table1
. I run the SELECT query on
Table2
and I would like to display the name of the ID found in
Table1
, not the ID itself.

Answer

I believe you're looking for an inner join;

SELECT 
t1.*
,t2.name 
FROM table1 t1
INNER JOIN table2 t2 
ON t1.ID = t2.user_id
WHERE p.id = '1'

This will give you everything from table1 that has a match in table2 and will return the name. Without seeing your schema I've taken a guess at the join field so this may need updating if necessary.

Comments