gpt4 book ai didi

c# - 存储过程,传递日期数组,以逗号分隔。转换错误

转载 作者:行者123 更新时间:2023-11-30 16:59:47 24 4
gpt4 key购买 nike

我正在尝试将以逗号分隔的日期字符串发送到我的存储过程,以在 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 String 和 SQLDbType NvarChar。

如有任何建议,我们将不胜感激!数据库:

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 PeakType=@PeakType))
and ((@DateList IS NULL and ContractDate between @StartDate and @EndDate)
or (@StartDate IS NULL and ContractDate in (@DateList)))
order by
ContractDate,SortOrder

最佳答案

您不能像这样在 IN 子句中使用 varchar 变量。您必须将其添加到动态 SQL 中才能执行,或者将其拆分为临时表/临时变量。

例如使用这个 SplitString功能你可以做这样的事情:

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

关于c# - 存储过程,传递日期数组,以逗号分隔。转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23251025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com