devxlogo

Using Where on Fields of Differing Types

Using Where on Fields of Differing Types

Question:
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?

Answer:
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

See also  Does It Make Sense to Splurge on a Laptop?
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist