2014-04-23 25 views
3

我想發送逗號分隔的日期字符串到我的存儲過程,在IN子句中使用。 但是,我收到錯誤「從字符串轉換日期和/或時間時轉換失敗。」存儲過程,傳遞日期列表,逗號分隔。轉換錯誤

我正試圖使用​​這些日期來查找匹配的價格。 C#:

StringBuilder LastDaysOfEveryMonth = new StringBuilder(); 
DataAccess da = new DataAccess(); 
SqlCommand cm = new SqlCommand(); 
cm.CommandType = CommandType.StoredProcedure; 
var pList = new SqlParameter("@DateList", DbType.String); 
pList.Value = LastDaysOfEveryMonth.ToString(); 
cm.Parameters.Add(pList); 
... 
cm.CommandText = "spCalculateRollingAverage"; 
DataSet ds = da.ExecuteDataSet(ref cm); 

調試時它,所傳遞的字符串的值是:

'2013-07-31','2013-08-30','2013-09-30','2013-10-31','2013-11-29','2013-12-31', 
'2014-01-31','2014-02-28','2014-03-31','2014-04-03', 

與的DbType字符串和SQLDbType NVARCHAR。

任何意見將不勝感激! SQL:

CREATE PROCEDURE [dbo].[spCalculateRollingAverage] 
@StartDate DateTime, 
@EndDate DateTime, 
@Commodity nvarchar(10), 
@PeakType nvarchar (10), 
@BaseID int, 
@NumberOfMonths int, 
@DateList nvarchar(MAX) 

AS 

    BEGIN 

    select TermDescription,ContractDate,Price,SortOrder into #tbtp from BaseTermPrice 
    inner hash join Term 
    on 
    Term.TermID = BaseTermPrice.TermID 
    where 
    BaseID = @BaseID and ((@PeakType IS NULL and PeakType is null) or 
    (@PeakType IS  NOT NULL and [email protected])) 
    and ((@DateList IS NULL and ContractDate between @StartDate and @EndDate) 
    or (@StartDate IS NULL and ContractDate in (@DateList))) 
    order by 
    ContractDate,SortOrder 
+0

對於初學者脫掉你逝去的字符串中的最後一個逗號。 – logixologist

回答

2

你不能在這樣一個IN子句中使用VARCHAR類型變量。您必須將其添加到要執行的動態SQL中,或者 - 將其分割爲臨時表/ temp變量。

例如使用此SplitString功能,你可以做這樣的事情:

or (@StartDate IS NULL and ContractDate in 
      (SELECT Name from dbo.SplitString(@DateList)))) 
相關問題