問題描述
如果我們包含 AND HostApplication 子句,此查詢將不起作用.
This query will not work if we include the AND HostApplication clause.
參數:
ALTER PROCEDURE [dbo].[updateNumbers_ArchiveDB]
(
@accountNumber varchar(50),
@accountType char(4),
@padding varchar(50),
@proc_dateStart datetime,
@proc_dateEnd datetime
)
這是動態 SQL:
set @q = 'Update ' + @cTableName +
' SET LogicalAccount = '+ @padding + @accountNumber +
' WHERE ProcessDate BETWEEN CAST('''+CONVERT(VARCHAR(20),@proc_dateStart)+''' AS DATE) AND CAST('''+CONVERT(VARCHAR(20),@proc_dateEnd)+''' AS DATE)' +
' AND HostApplication =' + '''+ @accountType +'''
這是我的執行聲明:
exec updateNumbers_ArchiveDB @accountNumber = N'1020',
@accountType = N'd',
@padding = N'123',
@proc_dateStart = '2014-01-30',
@proc_dateEnd = '2014-01-31'
如果我刪除 @accounttype
周圍的單引號:(''+@accounttype +'')
我得到這個錯誤:
If I remove a single quote around @accounttype
: (''+@accounttype +'')
I get this error:
消息 207,級別 16,狀態 1,第 1 行
無效的列名d".
Msg 207, Level 16, State 1, Line 1
Invalid column name 'd'.
使用 3 個引號,它可以正常運行而不會出錯,但不會進行任何更新.
With 3 quotes it works runs without error, but no updates are made.
使用 1 個引號 (('+@accounttype +'))
我得到:
With 1 quote (('+@accounttype +'))
I get:
消息 137,級別 15,狀態 2,第 1 行
必須聲明標量變量@accountType".
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@accountType".
我意識到在動態 SQL 中使用引號是一門藝術,但我沒有找到任何關于在動態 SQL 中使用 char 數據類型的資源.
I realize there is an art to using quotes in dynamic SQL, but I have not found any resources on using the char data type in dynamic SQL.
推薦答案
+ ''''+ @accountType +''''
應該修復它
這篇關于我的動態 SQL 查詢有什么問題?使用 char 數據類型的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!