2014-01-30 33 views
-1

我有一個名爲例如abc.cs的類。我使用自定義功能進行搜索的標準是這樣的:在C#中執行類中的存儲過程,ASP.NET

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) 
     { 

     } 
    } 

商店procedue這是我到目前爲止已經試過:

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的方式。

+0

http://www.techrepublic.com/blog/the-enterprise-cloud/generate-dynamic-sql-statements-in-sql-server/# 。 –

+0

@Neil Thompson我被困在一點,我將如何在where子句中傳遞列名。我讓用戶選擇列名,我將通過函數參數獲取列名的值。這實際上讓人困惑。 –

+1

你不能這樣做;你必須將整個查詢作爲一個字符串傳遞給sql server並使用Amit的解決方案,或者你可以構建一個動態where子句並從C#執行該數據庫對數據庫(參見http://stackoverflow.com/questions/17321281/是-有-A-更好路到動態積聚的-SQL WHERE子句高於通過-使用-1-1)。但是,請注意,您確實需要小心用戶傳遞給您的值,因爲這會爲SQL Inject樣式攻擊提供很多機會。 – dash

回答

0

您可以使用此...

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