![](/img/trans.png)
[英]How do I get quoted fields from a delimited string as a list of unquoted values using LINQ?
[英]How do I get the correct sql quoted string for a .NET DbType
我想運行一個將默認值約束添加到列的ALTER TABLE
。
我從.NET程序動態生成此語句。
既然構建ALTER TABLE
語句不支持參數,那么如何最好地格式化和引用該值(既然ALTER TABLE
語句不支持參數(給出錯誤“ ALTER TABLE語句中不允許變量”))。
.NET中是否有實用程序? 還是其他解決方案?
string.Format("alter table YourTable add constraint DF_YourTable_Col1 default '{0}'",
inputValue.Replace("'", "''"));
您可以在TSQL中執行此操作; 例如,假設您對命令進行參數化,傳入@DefaultValue
,即一個varchar
,它可能是也可能不是有效的TSQL文字。 因為我們正在編寫DDL,所以我們需要串聯和exec
,但是我們顯然不想盲目串聯,因為該值可能是非法的。 幸運的是, quotename
我們的所有需求。 默認情況下, quotename
輸出[qualified object names]
,但是您可以告訴它在單引號和雙引號文字中都以文字轉義模式運行。
因此,接受@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);
完整示例:
--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.