2014-03-19 62 views
0

我當前將sql語句分配給NVarchar,然後執行它。但我不喜歡這種工作方式。如何在Kentico查詢中使用可配置的Where子句

SQL

DECLARE @sqlStatement NVARCHAR(4000) 

SET @sqlStatement = N' 
    SELECT * 
    FROM CMS_User usr 
    WHERE 
    ( 
      usr.LastName LIKE ''%' + @Search + '%'' OR 
    )' 

IF(@SearchWhereClause IS NOT NULL) 
BEGIN 
    SET @sqlStatement = @sqlStatement+ N' AND (' + @SearchWhereClause + ')' 
END 

SET @sqlStatement = @sqlStatement+ N' ORDER BY usr.LastName' 

EXEC sp_executesql @statement = @sqlStatement 

代碼

QueryDataParameters parameters = new QueryDataParameters(); 
parameters.Add("@Search", prefixText); 

//set configurabel searchWhereClause 
string searchWhereClause = SettingsKeyProvider.GetStringValue("WhereClause"); 
if (string.IsNullOrEmpty(searchWhereClause)) 
{ 
     searchWhereClause = null; 
} 
parameters.Add("@SearchWhereClause", searchWhereClause); 

DataSet ds = ConnectionHelper.ExecuteQuery("custom.DocType.Query", parameters); 

回答

1

相反,你可以使用Kentico宏查詢:

SQL

SELECT * 
FROM CMS_User usr 
WHERE 
( 
    usr.LastName LIKE '%' + @Search + '%' OR 
) 
AND (usr.UserIsHidden IS NULL OR usr.UserIsHidden = 0) 
AND (##WHERE##) 
ORDER BY usr.LastName 

代碼

ConnectionHelper.ExecuteQuery(string queryName, QueryDataParameters parameters, 
    string where);