System.Data.SqlClient.SqlException:无效的列名'conferID'

时间:2015-05-05 15:38:40

标签: c# sql-server

尝试从数据库中检索会议的特定日期以显示在网页上。阅读会员ID,如下所示:

conferID = reader["ConferenceID"].ToString();

我希望页面只显示来自ConferenceID ='3'的日期,但是当我从下面的代码中删除(ConferenceID = conferID)时,我也从ConferenceID ='1'和ConferenceID ='2'获取日期。但是,如果我将(ConferenceID = conferID)添加回代码,则页面会中断。如果我将这些代码放在SQL中来测试和更改(ConferenceID = conferID)到(ConferenceID ='3'),它就可以了。我现在迷路了。任何帮助表示赞赏。

SqlCommand GetDates = new SqlCommand(@"
WITH x AS (
             select MAX(ConferenceID) as ConferenceID, row_number() over(order by D.Dates) as SN, D.Dates 
             from Conference as T 
                  inner join master..spt_values as N 
                  on N.number between 0 and datediff(day, T.ConferenceBeginDate, T.ConferenceEndDate) 
                  cross apply (select dateadd(day, N.number, T.ConferenceBeginDate)) as D(Dates) 
                  where N.type ='P' AND (ConferenceID = conferID) group by ConferenceID, D.Dates
                  )
SELECT ConferenceID, SN, Dates
FROM x
WHERE SN <> (Select MAX(SN) from x) AND (ConferenceID = conferID)
GROUP BY ConferenceID, SN, Dates", conn);

2 个答案:

答案 0 :(得分:5)

您需要将conferID添加为Parameter。试试这个

SqlCommand GetDates = new SqlCommand(@"
WITH x AS (
             select MAX(ConferenceID) as ConferenceID, row_number() over(order by D.Dates) as SN, D.Dates 
             from Conference as T 
                  inner join master..spt_values as N 
                  on N.number between 0 and datediff(day, T.ConferenceBeginDate, T.ConferenceEndDate) 
                  cross apply (select dateadd(day, N.number, T.ConferenceBeginDate)) as D(Dates) 
                  where N.type ='P' AND (ConferenceID = @ConferenceID) group by ConferenceID, D.Dates
                  )
SELECT ConferenceID, SN, Dates
FROM x
WHERE SN <> (Select MAX(SN) from x) AND (ConferenceID = @ConferenceID)
GROUP BY ConferenceID, SN, Dates", conn);

GetDates.Parameters.Add(new SqlParameter("@ConferenceID", conferID));

答案 1 :(得分:2)

请使用sql参数。

SqlCommand GetDates = new SqlCommand(@"
WITH x AS (
             select MAX(ConferenceID) as ConferenceID, row_number() over(order by D.Dates) as SN, D.Dates 
             from Conference as T 
                  inner join master..spt_values as N 
                  on N.number between 0 and datediff(day, T.ConferenceBeginDate, T.ConferenceEndDate) 
                  cross apply (select dateadd(day, N.number, T.ConferenceBeginDate)) as D(Dates) 
                  where N.type ='P' AND (ConferenceID = @conferId) group by ConferenceID, D.Dates
                  )
SELECT ConferenceID, SN, Dates
FROM x
WHERE SN <> (Select MAX(SN) from x) AND (ConferenceID = @conferId)
GROUP BY ConferenceID, SN, Dates", conn);

GetDates.Parameters.AddWithValue("@conferId", conferId);

这里的问题是您正在尝试引用不存在的字段。我假设您正在尝试引用可用的字符串,因此您必须将其添加为命名参数,然后通过此分配。

相关问题