Using Where on Fields of Differing Types

Using Where on Fields of Differing Types

I need to extract information using WHERE on fields in two different tables: one a text field, the other a numeric field. Both hold only numeric data. How can I do this?

If by the term text field you mean varchar, you can convert the column data using the STR function. And in the case of SQL Server, it will use the implicit conversion. So if you have this table:

NumberField int,           value 230VarcharField varchar(255), value 230These SQL statements will both work:SELECT * FROM TestTable WHERE STR(NumberField) = 230SELECT * FROM TestTable WHERE STR(VarcharField) = 230

If one of your fields is the actual text data type, you’ll have to use the Cast function to convert it to varchar. But this involves a slightly different syntax, so you’ll have to query the column data type or have some conditional logic if the column is numeric or text. For example:

SELECT * FROM TestTable WHERE CAST(TextField AS varchar) = 230


Share the Post: