DECLARE @pTbl NVARCHAR(20) = 'tblTPS'
DECLARE @sMD FLOAT = 3.3333333300000e-001
DECLARE @sIQ FLOAT = 000000000000.000e+000
DECLARE @Sql NVARCHAR(MAX)
SET @SQL ='UPDATE ' + CAST(@pTbl AS NVARCHAR) + ' SET fldND = (CASE WHEN fldND < ('+CAST(@sMD AS NVARCHAR)+' - (2 *
'+CAST(@sIQ AS NVARCHAR)+'))
THEN '+CAST(@sMD AS NVARCHAR)+' - (2 * '+CAST(@sIQ AS NVARCHAR)+') ELSE
(CASE WHEN fldND > ('+CAST(@sMD AS NVARCHAR)+'+(2 * '+CAST(@sIQ AS NVARCHAR)+')) THEN '+CAST(@sMD AS NVARCHAR)+' + (2 *
'+CAST(@sIQ AS NVARCHAR)+')END)END)'
PRINT @SQL
打印结果
UPDATE tblTPS SET fldND = (CASE WHEN fldND < (0.333333 - (2 *
0))
THEN 0.333333 - (2 * 0) ELSE
(CASE WHEN fldND > (0.333333+(2 * 0)) THEN 0.333333 + (2 *
0)END)END)
说明 在创建 SQL Dynamic 时,如果您尝试将 intiger 连接到字符串,则基本上是在连接多个字符串 SQL Server 尝试将字符串转换为 INT,因为 INT 具有更高的数据类型优先级。
当您尝试将字符串连接到 Sql Dynamic 并且您希望 SQL Dynamic 将其视为单独的字符串但不是动态字符串的一部分时,例如您正在传递字符串“John”然后您必须使用单引号传递给动态 Sql 时两次像这样
DECLARE @NAME NVARCHAR(20) = 'John'
DECLARE @Sql1 NVARCHAR(MAX)
SET @Sql1 = 'SELECT * FROM Table WHERE NAME IN ('''+ @NAME + ''')'
PRINT @Sql1
打印结果
SELECT * FROM Table WHERE NAME IN ('John')