gpt4 book ai didi

c# - 将 boolean 参数传递给 SQL Server 存储过程

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:45 26 4
gpt4 key购买 nike

我之前问过这个问题,我以为我找到了问题所在,但我没有。我在将 boolean 参数传递给存储过程时遇到问题。这是我的 C# 代码:

public bool upload = false;

protected void showDate(object sender, EventArgs e)
{
if (Radio1.Checked)
{
upload = true;
Radio2.Checked = false;
date_div.Visible = true;
date_div2.Visible = false;
}
}

protected void getMonthList()
{
selectedYear = year.SelectedValue.ToString();

SqlConnection connection = new SqlConnection(connString);

SqlCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;

connection.Open();

cmd.CommandText = "getMonth";
cmd.Parameters.Add("@year", SqlDbType.Int, 0).Value = Convert.ToInt32(selectedYear);
cmd.Parameters.AddWithValue("@upload", upload);

DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);

da.Fill(dt);

month.DataSource = dt;
month.DataTextField = "month";
month.DataValueField = "monthValue";
month.DataBind();
month.Items.Insert(0, new ListItem("Select", "0"));
}

这是存储过程 getMonth:

ALTER PROCEDURE [dbo].[getMonth] 
@year int,
@upload Bit
AS
BEGIN
IF @upload = 1
BEGIN
SELECT distinct datename(mm, Upload_date) month
,month (upload_date) monthValue
FROM dbo.RESOLVED
WHERE datepart(yyyy, upload_date) = @year
ORDER by 2
END
ELSE
BEGIN
SELECT distinct datename(mm, substring(CREATE_DT,1,2) + '.' + substring(CREATE_DT,3,2) + '.' + substring(CREATE_DT,5,4)) month
,month (substring(CREATE_DT,1,2) + '.' + substring(CREATE_DT,3,2) + '.' + substring(CREATE_DT,5,4)) monthValue

FROM dbo.RESOLVED
WHERE datepart(yyyy, substring(CREATE_DT,1,2) + '.' + substring(CREATE_DT,3,2) + '.' + substring(CREATE_DT,5,4)) = @year
ORDER by 2
END

存储过程应该填充下拉列表。它应该执行 IF 语句,但 IF 被跳过,而是执行了 ELSE。

最佳答案

我也倾向于指定 boolean 参数的类型。也许是这样的;

            SqlParameter param = new SqlParameter();
param.ParameterName = "@upload";
param.Value = upload;
param.DbType = System.Data.DbType.Boolean
cmd.Parameters.Add(param);

也许还可以使用断点甚至 System.Diagnostics.Debug.Write("@Upload is " + upload) 进行检查以确保您传递的是您认为传递的内容。

最后,我建议将您的 SqlConnectionSqlCommand using 中的语句 block 以确保在运行后清理资源。

关于c# - 将 boolean 参数传递给 SQL Server 存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17536093/

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