Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine which SQL data types require value to be quoted?

I need to send a command to a database. I know the names and data types of all the fields in the affected table, and I need to generate a command using them. My only problem is determining which column values are of data types that require quotes in TSQL - for example, if the field was a string Hello World of type varchar, I'd need to quote it, but if it were an int, 5, I wouldn't need to quote it.

I could use something like the following code, but it seems very inefficient. Can someone point me to a better way of doing this - possibly using a built in SQL server or C# feature?

public string QuoteStringIfDatatypeRequires(string columnName)
{
    if (DataTypes[columnName].Contains("date") || DataTypes[columnName].Contains("time") ||
        DataTypes[columnName].Contains("char") || DataTypes[columnName].Contains("text") ||
        DataTypes[columnName].Contains("binary") || DataTypes[columnName].Contains("image"))
    {
        return "'" + columnName + "'";
    }

    return columnName;
}
like image 327
John Humphreys Avatar asked Apr 19 '12 19:04

John Humphreys


People also ask

When using data what data types are surrounded by single quotes?

Values assigned to the TIME data type should be enclosed in single quotes, preceded by the case insensitive keyword TIME; for example, TIME '07:30:00'.

Do numbers need quotes in SQL?

A number is something you use for calculation. A number should not be quoted, since a number should never be stored in the database as a string.

What is SQL quoted identifier?

SET QUOTED_IDENTIFIER ON: With this option, SQL Server treats values inside double-quotes as an identifier. It is the default setting in SQL Server. In the above example, we see that it treats the string Rajendra. It checks for the column name and gives an error message.

How can someone determine the type of a value in SQL?

Use TYPE_NAME() to Get the Name of a Data Type in SQL Server In SQL Server, you can use the TYPE_NAME() function to return the name of a data type, based on its ID. This can be useful when querying a system view such as sys. columns that returns the type's ID but not its name.


1 Answers

You can quote everything, and that will be converted to the appropriate data type by database itself.

But that will be incorrect. Instead you need to use parameterized queries and send values as is:

command.Parameters.AddWithValue("@name", value);

or

command.Parameters.Add("@name", type, size).Value = value;

See MSDN.

like image 80
abatishchev Avatar answered Oct 05 '22 04:10

abatishchev