简体   繁体   中英

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.

I generate this statement dynamically from a .NET program.

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').

Is there a utility for that in .NET? Or another solution?

string.Format("alter table YourTable add constraint DF_YourTable_Col1 default '{0}'",
    inputValue.Replace("'", "''"));

You can do this in TSQL; for example, say you parameterize the command, passing in @DefaultValue , a varchar which may or may not be a valid TSQL literal. 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. Fortunately, quotename does everything we need. 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.

So our query that accepts @DefaultValue can build an SQL string:

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM