" Where"我的SQL的子句将根据提供的值而有所不同。我写了两个版本(动态和静态)。我读到如果我们有一个带有变量where子句的多个参数,那么Dynamic是要走的路。此外,这只是一个示例,我真正的SQL有更多的条件,但沿着这些方向的东西。这两种情况中哪一种是这种情况的正确选择?
动态SQL:
DECLARE @SQL NVARCHAR(max)='SELECT ID,Name,sex,street,city,state,zip,phone FROM Test';
DECLARE @whereSql VARCHAR(2000) = 'WHERE city= @City';
DECLARE @OrderBy VARCHAR(2000) = 'order by name';
IF(@Name IS NOT NULL)
BEGIN
SET @Name = @Name + '%'
SET @whereSql = @whereSql + ' ' + 'AND name like @Name';
end
IF(@Gender IS NOT NULL)
BEGIN
SET @whereSql = @whereSql + ' ' + 'AND sex =' + '@Gender';
END
IF(@Address IS NOT NULL)
BEGIN
SET @Address = '%' + @Address + '%'
SET @whereSql = @whereSql + ' ' + 'AND street like ' + '@Address';
END
SET @SQL = @SQL +' ' + @whereSql + ' '+ @OrderBy;
EXEC sp_executesql @SQL, N'@Gender VARCHAR(10), @Name VARCHAR(200), @Address VARCHAR(250)', @Gender,@Name,@Address;
静态SQL:
SELECT ID,Name,sex,street,city,state,zip,phone FROM Test T1 WHERE
(@Name IS NULL OR (T1.Name LIKE +'%'+ @Name + '%'))
AND
(@Gender is null OR (T1.sex = @Gender))
AND
(@Address is null or (T1.street LIKE +'%'+ @Address + '%'))