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;
}
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'.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With