我正在学习SQL,我希望你的建议,看看这段代码是否写得正确,还是更好的方法。 这个脚本创建:
允许检查IP是否为黑名单的SPROC 请告诉我!谢谢!
-- Black Listed Table
CREATE TABLE UtlBlacklistedIPs
(
octet1 TINYINT,
octet2 TINYINT,
octet3 TINYINT,
octet4 TINYINT
);
1 SPROC
-- Convert an IP address in 4 octet for db storing
CREATE PROCEDURE dbo.storeIPoctetsv1
@ip CHAR(15)
AS
BEGIN
SET NOCOUNT ON
INSERT UtlBlacklistedIPs(octet1, octet2, octet3, octet4)
SELECT
CONVERT(TINYINT, PARSENAME(@ip, 4)),
CONVERT(TINYINT, PARSENAME(@ip, 3)),
CONVERT(TINYINT, PARSENAME(@ip, 2)),
CONVERT(TINYINT, PARSENAME(@ip, 1))
END
2 SPROC
-- SPROC check if an IP address has been black listed
CREATE PROCEDURE dbo.sprocCheckIp
@ip CHAR(15)
AS
BEGIN
SET NOCOUNT ON
DECLARE
@octet1 tinyint,
@octet2 tinyint,
@octet3 tinyint,
@octet4 tinyint;
SET @octet1 = CONVERT(tinyint, PARSENAME(@ip, 4));
SET @octet2 = CONVERT(tinyint, PARSENAME(@ip, 3));
SET @octet3 = CONVERT(tinyint, PARSENAME(@ip, 2));
SET @octet4 = CONVERT(tinyint, PARSENAME(@ip, 1));
IF EXISTS (
SELECT octet1, octet2, octet3, octet4
FROM UtlBlacklistedIPs
WHERE
octet1 =@octet1
AND octet2 =@octet2
AND octet3 =@octet3
AND octet4 =@octet4
)
BEGIN
PRINT 'Ip: '+@ip+' is black listed'
END
ELSE
BEGIN
PRINT 'Ip: '+@ip+' is NOT black listed'
END
END
一些值
-- Insert dummy values
DECLARE @i INT
SET @i = 0
WHILE @i < 2000
BEGIN
EXEC dbo.storeIPoctetsv1 @ip = '204.71.34.21'
EXEC dbo.storeIPoctetsv1 @ip = '12.38.145.32'
EXEC dbo.storeIPoctetsv1 @ip = '127.0.0.1'
SET @i = @i + 1
END
使用SPROC
-- Use SPROc
EXEC dbo.sprocCheckIp '125.254.125.111' -- NOT black listed Ip
EXEC dbo.sprocCheckIp '204.71.34.21' -- black listed Ip
答案 0 :(得分:3)
我假设您将在数据库之外使用它,大概是在.NET中?在那种情况下,我会重新构建这样的结构:
RETURN
,而不是PRINT
)Ip
编写类int[] ToOctets(string ip)
会更好。您将使用它:var octs = Ip.ToOctets("213.82.158.93")
答案 1 :(得分:1)
我同意Thomas的意见,但确实有一个问题:为什么要将IP存储在4个单独的列中?如果练习的全部内容是跟踪“黑名单的IP地址”,那么你何时需要只检查一段IP地址 - 你不会总是看着整个事情吗?因此,分割/重新组合八位字节似乎是不必要的。它也会让你写出很多额外的T-SQL。