sql server有两个转义符:
第一个转义符是单引号 (')
单引号 (') 默认情况下, 单引号 (') 是字符串的边界符, 如果在字符串中包含 单引号 ('), 则必须使用两个单引号 ('), 第1个单引号 (')就是转义符。
示例:
下面是条错误的sql,
INSERT INTO Cogs_PurchaseSale( CreateTime,UpdateTime,ApDate, Type,Change,Currency,ExchangeRate, [Date],StoreCode,ItemColor,Qty, ProfitCenter,CreditNote) SELECT getdate(), getdate(), '2019-11-01', case when LEN(isNull(sm.Type,'StockMovement'))>0 then sm.Type else 'StockMovement' end, 'Decrease', 'SYSTEM_LOCAL_CURRENCY','1', max(sm.[Date]), LEFT(sm.RecipientWarehouse,4), sm.ItemCode+sm.ColorCode, sum(sm.Qty), max(sm.ProfitCenter),max(sm.Remark) FROM Cogs_StockMovement as sm WHERE sm.APDate='2019-11-01' AND LEN(sm.RecipientWarehouse)>0 GROUP BY sm.Type, sm.RecipientWarehouse, sm.ItemCode, sm.ColorCode
我需要将这条sql记录到表里
$failmsg=" INSERT INTO Cogs_PurchaseSale(CreateTime,UpdateTime,ApDate,Type,Change,Currency,ExchangeRate,[Date],StoreCode,ItemColor,Qty,ProfitCenter,CreditNote) SELECT getdate(), getdate(), '2019-11-01', case when LEN(isNull(sm.Type,'StockMovement'))>0 then sm.Type else 'StockMovement' end, 'Decrease', 'SYSTEM_LOCAL_CURRENCY','1', max(sm.[Date]), LEFT(sm.RecipientWarehouse,4), sm.ItemCode+sm.ColorCode, sum(sm.Qty), max(sm.ProfitCenter),max(sm.Remark) FROM Cogs_StockMovement as sm WHERE sm.APDate='2019-11-01' AND LEN(sm.RecipientWarehouse)>0 GROUP BY sm.Type, sm.RecipientWarehouse, sm.ItemCode, sm.ColorCode";
$sql="update Cogs_TaskList set FailDesc='".str_replace("'", "''", ($failmsg))."',UpdateTime='".date("Y-m-d H:i:s")."' where ID=".$id; $res= $dbobj->query($sql);
这里处理的方式是str_replace将单引号替换成两个单引号
另一个转义符是双引号(")
当SET QUOTED_IDENTIFIER OFF时, "是字符串边界符, 字符串中的"必须用两个"表示。