[英]How do I get the correct sql quoted string for a .NET DbType
I want to run an ALTER TABLE
that adds a default value constraint to a column. 我想运行一个将默认值约束添加到列的ALTER TABLE
。
I generate this statement dynamically from a .NET program. 我从.NET程序动态生成此语句。
How do I best format and quote the value when building my sql - now that ALTER TABLE
statements does not support parameters (Gives the error 'Variables are not allowed in the ALTER TABLE statement'). 既然构建ALTER TABLE
语句不支持参数,那么如何最好地格式化和引用该值(既然ALTER TABLE
语句不支持参数(给出错误“ ALTER TABLE语句中不允许变量”))。
Is there a utility for that in .NET? .NET中是否有实用程序? Or another solution? 还是其他解决方案?
string.Format("alter table YourTable add constraint DF_YourTable_Col1 default '{0}'",
inputValue.Replace("'", "''"));
You can do this in TSQL; 您可以在TSQL中执行此操作; for example, say you parameterize the command, passing in @DefaultValue
, a varchar
which may or may not be a valid TSQL literal. 例如,假设您对命令进行参数化,传入@DefaultValue
,即一个varchar
,它可能是也可能不是有效的TSQL文字。 Because we are writing DDL, we will need to concatenate and exec
, however we clearly don't want to blindly concatenate, as the value could be illegal. 因为我们正在编写DDL,所以我们需要串联和exec
,但是我们显然不想盲目串联,因为该值可能是非法的。 Fortunately, quotename
does everything we need. 幸运的是, quotename
我们的所有需求。 By default, quotename
outputs [qualified object names]
, but you can tell it to operate in literal escaping mode, for both single-quote and double-quote literals. 默认情况下, quotename
输出[qualified object names]
,但是您可以告诉它在单引号和双引号文字中都以文字转义模式运行。
So our query that accepts @DefaultValue
can build an SQL string: 因此,接受@DefaultValue
的查询可以构建一个SQL字符串:
declare @sql nvarchar(4000) = 'alter table ...';
-- ... blah
-- append the default value; note the result includes the outer quotes
@sql = @sql + quotename(@DefaultValue, '''');
-- ... blah
exec (@sql);
Full example: 完整示例:
--drop table FunkyDefaultExample
create table FunkyDefaultExample (id int not null)
declare @tableName varchar(20) = 'FunkyDefaultExample',
@colName varchar(20) = 'col name',
@defaultValue varchar(80) = 'test '' with quote';
-- the TSQL we want to generate to exec
/*
alter table [FunkyDefaultExample] add [col name] varchar(50) null
constraint [col name default] default 'test '' with quote';
*/
declare @sql nvarchar(4000) = 'alter table ' + quotename(@tablename)
+ ' add ' + quotename(@colName) + 'varchar(50) null constraint '
+ quotename(@colName + ' default') + ' default '
+ quotename(@defaultValue, '''');
exec (@sql);
-- tada!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.