您可以使用 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