您可以使用PARSENAME函數將IP地址值分成四部分並分別進行比較。
創建並填充測試數據腳本:
CREATE TABLE ipaddresses
(
ip VARCHAR(20) NOT NULL
);
INSERT INTO ipaddresses (ip) VALUES
('192.12.34.12'),
('192.12.#.12'),
('192.#.34.12');
方案1
DECLARE @userip VARCHAR(20)
SET @userip = '192.56.34.12'
;WITH ips AS
(
SELECT REPLACE(ip, '#', '%') AS ip
FROM ipaddresses
)
SELECT COUNT(ip) AS validcount
FROM ips
WHERE PARSENAME(@userip, 1) LIKE PARSENAME(ip, 1)
AND PARSENAME(@userip, 2) LIKE PARSENAME(ip, 2)
AND PARSENAME(@userip, 3) LIKE PARSENAME(ip, 3)
AND PARSENAME(@userip, 4) LIKE PARSENAME(ip, 4);
VALIDCOUNT
----------
1
方案2
DECLARE @userip VARCHAR(20)
SET @userip = '191.12.34.12'
;WITH ips AS
(
SELECT REPLACE(ip, '#', '%') AS ip
FROM ipaddresses
)
SELECT COUNT(ip) AS validcount
FROM ips
WHERE PARSENAME(@userip, 1) LIKE PARSENAME(ip, 1)
AND PARSENAME(@userip, 2) LIKE PARSENAME(ip, 2)
AND PARSENAME(@userip, 3) LIKE PARSENAME(ip, 3)
AND PARSENAME(@userip, 4) LIKE PARSENAME(ip, 4);
VALIDCOUNT
----------
0
運氣好的時候,我們向IPv6遷移,哈哈。 – Styxxy
此外,我懷疑這個例子是過於簡化,它會需要超過五個比較。也許...... heh –
應該是15,假設你不需要匹配#。#。#。# –