SQL Server 2008 R2存储过程不起作用(visual c#)
作者:互联网
我在过去一周左右搜索并尝试了不同的东西,我的问题可能是通过谷歌找到答案.
如果我在SQL Server Management Studio中执行此查询并将参数@zoekterm替换为’%something%’,它可以正常工作并返回我想要的结果.但是当我从C#调用相同的程序时,它什么也没有返回.
这是一个错误还是我那么愚蠢?
这是C#中存储过程和函数的代码,(我知道我应该使用switch case …)
存储过程:
-- =============================================
-- 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();
}
解决方法:
你不要把引号放在参数中(那些是表示文字);它应该是:
zoekterm.Value = "%"+textBox2.Text+"%";
它目前失败,因为如果文本是“abc”,它正在查找以单引号开头和结尾的字符串,并包含“abc”.在SQL术语中,您要求它:
LIKE '''%abc%'''
标签:c,stored-procedures,sql-server-2008-r2 来源: https://codeday.me/bug/20190621/1255996.html