我将如何将其保存到存储过程?并在c#?
中运行存储过程string a = "Select * from EmpTable Where EmpName Like @SearchItem";
using (SqlCommand SqlCommand = new SqlCommand(" "+ a +" ", myDatabaseConnection))
{
SqlCommand.Parameters.AddWithValue("@SearchItem", "%" + textBox1.Text + "%");
}
答案 0 :(得分:0)
存储过程:
CREATE PROCEDURE SearchSP
@SearchItem nvarchar(MAX)
AS
BEGIN
Select *
from EmpTable
Where EmpName Like '%' + @SearchItem + '%'
END
GO
代码:
using (SqlCommand cmd= new SqlCommand("SearchSP", myDatabaseConnection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SearchItem", textBox1.Text);
//rest of the code
}
答案 1 :(得分:0)
你说什么是你想要的字符串消失并调用存储过程而不是内部有这个SQL代码?如果是这样的话......
假设SQL Server 2008管理工作室..
在管理工作室中展开"数据库" ,然后展开"可编程性" ... 右键单击“创建新存储过程”并删除其中的所有代码。
然后键入以下内容。
USE [YourDataBaseName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[AnyName]
@SearchItem as nvarchar(MAX)
AS
Select * from EmpTable Where EmpName Like @SearchItem
单击运行/执行并刷新数据库,如果查看存储的proc文件夹,则应该看到新的存储过程。
然后在您的(假设C#.Net )代码中。
public string GetUserFinal(string _userInput)
{
string temp = "";
using (SqlConnection myConn = new SqlConnection(Conn))
{
using (SqlCommand myCommand = new SqlCommand())
{
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = "dbo.your procedure name";
myCommand.Parameters.AddWithValue("@SearchItem", _userInput);
SqlDataReader reader = myCommand.ExecuteReader();
myCommand.Connection = myConn;
While (reader.read())
{
//populate a string? or do something else?
}
}
}
return temp;
}
更好的方法是强力输入所有这些。所以我会创建一个模型,无论你现在的字段和类型是什么,然后创建一个列表并遍历该列表以从该函数绑定。但是,正如您可以看到基础知识,这应该只是检查语法。
答案 2 :(得分:0)
创建如下所示的存储过程:
Create Procedure dbo.Test
@SearchItem
AS
BEGIN
BEGIN TRY
IF EXISTS(SELECT 1 FROM dbo.Table WHERE EmpName LIKE '%'+@SearchItem+'%')
SELECT * FROM dbo.Table WHERE EmpName LIKE '%'+@SearchItem+'%'
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS 'ErrorNumber', ERROR_MESSAGE() AS 'ErrorMessage', ERROR_SEVERITY() AS 'ErrorSeverity', ERROR_STATE() AS 'ErrorState', ERROR_LINE() AS 'ErrorLine'
RETURN ERROR_NUMBER()
END CATCH
END
现在您可以在代码隐藏中引用此sp,如下所示:
SqlConnection xconn=new SqlConnection(Write your connection string);
SqlCommand xcommand=new SqlCommand("Test",xconn);
xcommand.CommandType=CommandType.StoredProcedure;
xcommand.Parameters.AddWithValue("@SearchItem",DbType.String,txtBox1.Text);
xconn.Open();
xCommand.ExecuteNonQuery();
xconn.Close();
答案 3 :(得分:-1)
这将是您的存储过程,(尚未测试代码):
CREATE PROCEDURE TestStoredProc
@SearchItem nvarchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
Select *
from EmpTable
Where EmpName Like '%' + @SearchItem + '%'
END
GO
然后在代码端执行此操作:
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("TestStoredProc", conn) {
CommandType = CommandType.StoredProcedure, Parameters.AddWithValue("@SearchItem",textbox.Text)}) {
}