SQLDatasource中的静态WHERE子句

时间:2012-09-18 07:12:00

标签: c# sql sql-server sqldatasource

我需要根据要在运行时传递的Businessunit值执行查询。如果businessunit为null,则不应执行AND条件,如果它不为null,则必须采用传递的businessunit。

// SQL查询

SELECT nvrEmpCode, nvrEmpName 
FROM tblHRIMS_EmployeeDetail
WHERE (intCategoryID NOT IN (0, 1)) AND (nvrResigned = 'No') 
AND nvrBusinessunit=

所有这些必须在SQLDatasource中完成,而不是作为StoredProcedure完成。怎么做到这一点?

3 个答案:

答案 0 :(得分:1)

您的WHERE条件应该是这样的:

WHERE (intCategoryID NOT IN (0, 1)) AND (nvrResigned = 'No') 
AND (@businessunit IS NULL OR nvrBusinessunit=@businessunit)

答案 1 :(得分:1)

假设您使用的是SQL Client:

SELECT nvrEmpCode, nvrEmpName 
FROM tblHRIMS_EmployeeDetail
WHERE (intCategoryID NOT IN (0, 1)) AND (nvrResigned = 'No') 
AND (nvrBusinessunit=@BU OR @BU is null)

然后你必须为参数传递一个值:

command.Parameters.AddWithValue(@BU, yourValue)

答案 2 :(得分:0)

SELECT        nvrEmpCode, nvrEmpName, @Businessunit AS varchar

FROM            tblHRIMS_EmployeeDetail
WHERE        (intCategoryID NOT IN (0, 1)) AND (nvrResigned = 'No') 
AND (nvrBusinessUnit = (CASE WHEN @Businessunit = '' THEN nvrBusinessunit ELSE @Businessunit END))