簡體   English   中英

使用nvarchar(MAX)生成查詢,但在where子句中轉換失敗

[英]Using nvarchar(MAX) to build query, but conversion fails in where clause

我有一個存儲過程,該存儲過程使用名為@Command (nvarchar(MAX))的變量。 然后,根據給定的輸入,相應地添加參數。

declare @Command nvarchar(max)
if(@CaseFileID IS NOT NULL)
BEGIN
select @Command='
  select [ServerCredentialsID],[CaseFileID],EIKSLT.[LocationType],EPT.PaymentType,[TaskID],[DateActive]
      ,[LengthOfPurchase],[Username],[Password],[IPDomain],[Port],[DES],[Website],[AmountPaid],[Latitude]
      ,[Longitude],[HasAttachments],[TimeStamp],[CaseElement],[Temporary],[StatusID] 
      FROM Element17a_IKSServerCredentials EIKSSC 
      JOIN ElementsIKSLocationTypes EIKSLT ON EIKSSC.LocationBeingUsedID= EIKSLT.IKSLocationBeingUsedID 
      JOIN ElementsPaymentTypes EPT ON EIKSSC.PaymentMethodID=EPT.PaymentTypeID 
      where  EIKSSC.CaseFileID='''+cast(@CaseFileID as nvarchar(MAX))+''' '

@CaseFileID聲明為int,在表中為int。 當我嘗試

where  EIKSSC.CaseFileID = ' + @CaseFileID + ' '

那么該值甚至都不會顯示(在錯誤中看起來像是"EIKSSC.CaseFileID= '"

我就是不明白。

注意:SQL Server 2008管理工作室

這是因為@CaseFileID是VARCHAR,即使您沒有顯示它也是如此。
您的IF應該是

if(@CaseFileID > '')

而且,即使那行不通,您也需要交換到LEFT聯接,因為INNER JOIN會刪除其他2個表中無法匹配的記錄。

最后,由於CaseFileID是一個i​​nt,因此不需要引號。 即使SQL Server在WHERE子句中隱式將9強制轉換為整數9,也沒有必要。

declare @Command nvarchar(max)
if(@CaseFileID > '')
BEGIN
select @Command='
  select [ServerCredentialsID],[CaseFileID],EIKSLT.[LocationType],EPT.PaymentType,[TaskID],[DateActive]
      ,[LengthOfPurchase],[Username],[Password],[IPDomain],[Port],[DES],[Website],[AmountPaid],[Latitude]
      ,[Longitude],[HasAttachments],[TimeStamp],[CaseElement],[Temporary],[StatusID] 
      FROM Element17a_IKSServerCredentials EIKSSC 
      LEFT JOIN ElementsIKSLocationTypes EIKSLT ON EIKSSC.LocationBeingUsedID= EIKSLT.IKSLocationBeingUsedID 
      LEFT JOIN ElementsPaymentTypes EPT ON EIKSSC.PaymentMethodID=EPT.PaymentTypeID 
      where  EIKSSC.CaseFileID='+cast(@CaseFileID as nvarchar(MAX))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM