我已經有一個搜索過濾器的存盤程序,但是它很復雜而且很長,如何增強存盤程序代碼?
我有 3 個搜索過濾器:組、鍵和標簽,這些搜索過濾器相互關聯。
我的存盤程序代碼:
IF (@group <> '' AND @key <> '' AND @label <> '')
BEGIN
SET @statement =
@statement ' WHERE ([group] LIKE ''%' @group '%'' AND [key] LIKE ''%' @key '%'' AND [label] LIKE ''%' @label '%'')'
END
ELSE IF (@group <> '' AND @key <> '')
BEGIN
SET @statement =
@statement ' WHERE ([group] LIKE ''%' @group '%'' AND [key] LIKE ''%' @key '%'')'
END
ELSE IF (@key <> '' AND @label <> '')
BEGIN
SET @statement =
@statement ' WHERE ([key] LIKE ''%' @key '%'' AND [label] LIKE ''%' @label '%'')'
END
ELSE IF (@label <> '' AND @group <> '')
BEGIN
SET @statement =
@statement ' WHERE ([label] LIKE ''%' @label '%'' AND [group] LIKE ''%' @group '%'')'
END
ELSE IF (@group <> '')
BEGIN
SET @statement
= @statement ' WHERE [group] LIKE ''%' @group '%'''
END
ELSE IF (@key <> '')
BEGIN
SET @statement
= @statement ' WHERE [key] LIKE ''%' @key '%'' '
END
ELSE IF (@label <> '')
BEGIN
SET @statement
= @statement ' WHERE [label] LIKE ''%' @label '%'''
END
如何修改代碼更簡單?
uj5u.com熱心網友回復:
SET @statement =
@statement ' WHERE
( (@group<>'' and [group] LIKE ''%' @group '%''') or (@group='' and 1=1))
( (@key <>'' and [key] LIKE ''%' @key '%''') or (@key ='' and 1=1))
( (@label <>'' and [label] LIKE ''%' @label '%''') or (@label ='' and 1=1))
請嘗試使用上述方式使用sql注入
uj5u.com熱心網友回復:
過去,我在使用表示多個可選搜索條件的輸入引數創建存盤程序時使用了以下模式。這種技術的優點是
- 沒有動態 SQL
- 查詢很干凈
- WHERE 子句有多個 AND(沒有 OR),允許 SQL 使用您在搜索列上可能擁有的任何索引
這只是一個示例,但希望您能理解并以此為基礎。
-- Procedure Input Arguments
DECLARE
@IntExample INT = NULL
,@StringExample VARCHAR(50) = NULL;
-- Constants
DECLARE @MinInt32 INT = (-2147483648), @MaxInt32 INT = 2147483647;
-- Input Argument Validation
DECLARE @IdMin INT = @MinInt32, @IdMax INT = @MaxInt32;
IF (@IntExample IS NOT NULL)
BEGIN
SET @IdMin = @IntExample;
SET @IdMax = @IntExample;
END
DECLARE @DescFilter NVARCHAR(50) = '%';
IF (@StringExample IS NOT NULL)
BEGIN
SET @DescFilter = '%' @StringExample '%';
END
-- Procedure Query
SELECT *
FROM dbo.MyTable
WHERE
(
Id BETWEEN @IdMin AND @IdMax
AND [Description] LIKE @DescFilter
);
uj5u.com熱心網友回復:
假設您只是為了 WHERE 子句而構建動態 SQL。
由于短路,這個可能會表現最好
SELECT *
FROM dbo.MyTable
WHERE
((@group = '') OR ([group] LIKE '%' @group '%'))
AND ((@key = '') OR ([key] LIKE '%' @key '%'))
AND ((@label = '') OR ([label] LIKE '%' @label '%'))
這也可以,但它會占用更多資源,并且不像上面的那樣可讀。
SELECT *
FROM dbo.MyTable
WHERE
([group] LIKE STUFF('%%', 2, 0, @group) )
AND ([key] LIKE STUFF('%%', 2, 0, @key) )
AND ([label] LIKE STUFF('%%', 2, 0, @label) )
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/528847.html
上一篇:列出每年購買過的(忠實)客戶
下一篇:在SQL中按資料型別選擇列
