C# 在C、ASP.NET中执行类中的存储过程
我有一门课叫abc.cs。我正在使用自定义函数搜索以下条件:C# 在C、ASP.NET中执行类中的存储过程,c#,asp.net,sql-server,stored-procedures,C#,Asp.net,Sql Server,Stored Procedures,我有一门课叫abc.cs。我正在使用自定义函数搜索以下条件: public System.Data.DataTable myFunction(string SearchText, string ColumnName, string SearchCriteria) { // ColumnName is the name of the column in db table as shown below in // query e.g a , b , c ,
public System.Data.DataTable myFunction(string SearchText, string ColumnName, string
SearchCriteria)
{
// ColumnName is the name of the column in db table as shown below in
// query e.g a , b , c , d, e
try
{
string strQuery = "SELECT a,b,c,d,e FROM myTable ";
SearchText = SearchText.Trim().Replace("[", "[[]");
SearchText = SearchText.Trim().Replace("'", "''");
SearchText = SearchText.Trim().Replace("%", "[%]");
SearchText = SearchText.Trim().Replace("_", "[_]");
if (SearchText != "")
{
strQuery += " where " + ColumnName + " LIKE ";
if (SearchCriteria == "x")
{
strQuery += "'" + SearchText + "%'";
}
else if (SearchCriteria == "y")
{
strQuery += "'%" + SearchText + "'";
}
else if (SearchCriteria == "z")
{
strQuery += "'%" + SearchText + "%'";
}
else
{
strQuery += "'" + SearchText + "'";
}
}
strQuery += "ORDER BY b";
}
catch (Exception E)
{
}
}
到目前为止我尝试过的商店程序:
USE [dbName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[abc]
@SearchText nvarchar(100)
AS
BEGIN
SELECT a,b,c,d,e FROM myTable ;
-- what should be the criteria here.
END
GO
我被困在如何在存储过程中的条件中使用searchText的问题上,而不是在myFunction中使用searchText的方法。您可以使用这个
USE [dbName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[abc]
@SearchText nvarchar(100)
AS
BEGIN
DECLARE @sql nvarchar(4000)
SET @sql = 'SELECT a,b,c,d,e FROM myTable ' + @SearchText
-- what should be the criteria here.
EXEC sp_executesql @sql
END
GO
@Neil Thompson我被困在where子句中如何传递列名的问题上。我让用户选择列名,我将通过函数参数获得列名的值。这实际上是在制造混乱。你不能这样做;您要么必须将整个查询作为字符串传递给SQLServer并使用Amit的解决方案,要么可以构建一个动态where子句,并根据数据库see从C执行该sql。但是,请注意,您确实需要小心用户传递给您的值,因为这为SQL注入式攻击提供了很多机会。