简体   繁体   中英

SQL Server 2008 R2 stored procedure doesn't work (visual c#)

I have searched and tried different things for the past week or so and my problem is possibly to specific to find an answer through google.

If I execute this query in SQL Server Management Studio and replace the parameter @zoekterm with '%something%' , it works fine and returns the result that I want. But when I call the same procedure from C# it returns nothing.

Is this a bug or am I just that stupid?

Here's code of stored procedure and function in C#, (I know I should have used switch case...)

Stored procedure:

-- =============================================
-- Author:      Daan
-- Create date: 
-- Description: 
-- =============================================
ALTER PROCEDURE [dbo].[quick_bedrijf] 
    -- Add the parameters for the stored procedure here
    @zoekterm varchar(100) = 0
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT bedrijf.bedrijf_nr, bedrijf.zoeknaam, bedrijf.plaats
    FROM bedrijf
    WHERE zoeknaam LIKE @zoekterm AND NIETactief = 0

    ORDER BY bedrijf.zoeknaam, bedrijf.plaats 
END

C#:

private void snel_zoek2()
{
    listView1.Items.Clear();

    con.Open();
    if (type == 1)
    {
         command1 = new SqlCommand("quick_project", con);
         colnum = 5;
    }
    else if (type == 2)
    {
         command1 = new SqlCommand("quick_bedrijf", con);
         colnum = 3;
    }
    else if (type == 3)
    {
         command1 = new SqlCommand("quick_persoon", con);
         colnum = 4;
    }
    command1.CommandType = CommandType.StoredProcedure;
    SqlParameter zoekterm = command1.Parameters.Add("@zoekterm", SqlDbType.VarChar, 100);
    zoekterm.Direction = ParameterDirection.Input;
    //command1.Parameters.Add(new SqlParameter("@zoekterm", SqlDbType.VarChar)).Value = " '%zee%'";// + textBox2.Text.ToString()+
    zoekterm.Value = "'%"+textBox2.Text.ToString()+"%'";
    // MessageBox.Show(zoekterm.Value.ToString());
    SqlDataAdapter adapt = new SqlDataAdapter();
    DataTable dt = new DataTable();
    adapt.SelectCommand = command1;
    adapt.Fill(dt);
    dataGridView1.BindingContext = new BindingContext();
    dataGridView1.DataSource = dt;

    con.Close();
}

You don't put the quotes into the parameter (those are to signify a literal ); it should be:

zoekterm.Value = "%"+textBox2.Text+"%";

It is failing currently because if the text is "abc", it is looking for a string that starts and ends with a single quote and includes "abc". In SQL terms, you were asking it for:

LIKE '''%abc%'''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM