如何用两个不同的查询编写存储过程

how to write stored procedure with two different queries

其实我是数据库初学者.. 我写了一个存储过程,我想在 c# winform 应用程序中使用 if else 从两个不同的 tables 中获取结果,例如我有两个 tables,其中一列是 'comp_number' .. 现在我已经编写了一个在按钮单击事件上执行的存储过程

ALTER procedure [dbo].[complainVehicle_sp]
as
DECLARE @compno int


if @compno is not null  

begin

    select compno,compdate,regno,engineno,mcode from dbo.complainVehicle 
    where compno =  @compno 

end

else 

begin

   select compno,recoverydt,recoverytime,statuscode from dbo.complainRecovery
   where compno =  @compno   

end

现在我想要如果 Compno 匹配 table complainVehicle 它会显示针对此的结果,如果它与 table complainRecovery 匹配向我显示该记录的结果,否则它将不显示任何记录..

这是我的 C# 代码

  string str = @"Data Source=.;Initial Catalog=----;Integrated Security=False;User ID=sa;Password=----;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
            SqlConnection cnn = null;


            try
            {
                cnn = new SqlConnection(str);
                cnn.Open(); //open the connection

            }


            catch (SqlException err) 
            {
                Console.WriteLine("Error: " + err.ToString());
            }
            finally
            {
                if (cnn != null)
                {
                    cnn.Close(); 
                }
            } 


            if (textBox1.Text.Trim().Length == 0)

            {MessageBox.Show("No Record");}

            else if (textBox1.Text.Trim().Length  > 0)  
            {

                cnn.Open();
                SqlCommand cmd2 = new SqlCommand();
                cmd2.Connection = cnn;
                cmd2.CommandType = CommandType.StoredProcedure;
                cmd2.CommandText = "complainVehicle_sp";
                cmd2.Parameters.Add("@compno", System.Data.SqlDbType.NVarChar).Value = textBox1.Text.ToString();
                cmd2.ExecuteNonQuery();
                SqlDataAdapter da = new SqlDataAdapter(cmd2);
                DataSet ds = new DataSet();
                da.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];
                cnn.Close();

当我在文本框中输入 compno 并单击 sumbit 时,它显示错误 `'System.Data.SqlClient.SqlException' 类型的未处理异常发生在 System.Data.dll

其他信息:过程 complainVehicle_sp 没有参数,但提供了参数。`

...非常感谢大家的帮助..在此先感谢大家

在您的代码中,您使用了 DECLARE @compno int,它在过程主体中创建了一个局部变量。 @compno 变量无法从存储过程上下文外部访问,并且它对调用该过程的 C# 代码没有任何意义:

cmd2.Parameters.Add(
    "@compno", 
    System.Data.SqlDbType.NVarChar).Value = textBox1.Text.ToString();

因此,要解决您的问题,首先,将存储过程更改为接受参数

ALTER PROCEDURE [dbo].[complainVehicle_sp]
-- declare a parameter @compono to the procedure
    @compno INT
as ...
BEGIN
    IF @compno IS NOT NULL
    BEGIN
        SELECT compno,compdate,regno,engineno,mcode 
        FROM dbo.complainVehicle 
        WHERE compno = @compno 
    END
    ELSE
    BEGIN
        SELECT compno,recoverydt,recoverytime,statuscode 
        FROM dbo.complainRecovery
        WHERE compno =  @compno   
    END
END

其次,您必须在 C# 代码中添加适当的参数类型:

cmd2.Parameters.Add(
    "@compno", 
    System.Data.SqlDbType.Int).Value = int.Parse(textBox1.Text);

由于参数在存储过程定义中声明为INT,您需要使用System.Data.SqlDbType.Int并通过调用int.Parse(textBox1.Text).

提供有效的整数值

有关创建存储过程和参数选项的详细信息,请参阅 T-SQL Stored Procedure Syntax

首先,你必须用参数声明你的过程,然后你可能想使用 EXISTS 来检查每个 table,像这样;

alter procedure [dbo].[complainVehicle_sp] (@compno int)
as

if (exists (select 1 from dbo.complainVehicle where compno = @compno ) )
begin
    select compno,compdate,regno,engineno,mcode from dbo.complainVehicle 
    where compno =  @compno 
end
else
if (exists (select 1 from dbo.complainRecovery where compno = @compno ) )
begin
   select compno,recoverydt,recoverytime,statuscode from dbo.complainRecovery
   where compno =  @compno   
end

您还需要正确指定参数的类型;

cmd2.Parameters.Add("@compno", System.Data.SqlDbType.Int).Value = textBox1.Text.ToString();