我能想到的最简单的方法是创建一个函数,如fnCheckIP
,并在约束中使用此函数。
没有必要使用UDF。
create function fnCheckIP(@ip varchar(15)) returns bit
AS
begin
if (@ip is null)
return null
declare @num1 int
declare @num varchar(15)
declare @pos int
while (@ip is not null)
begin
set @pos = IsNull(NullIf(charindex('.', @ip), 0), Len(@ip) + 1)
set @num = substring(@ip, 1, @pos - 1)
if (isnumeric(@num) = 0) or (not cast(@num as int) between 0 and 255)
return cast(0 as bit)
if (len(@ip) - @pos <= 0)
set @ip = null
else
set @ip = NullIf(substring(@ip, @pos + 1, len(@ip) - @pos), '')
end
return cast (1 as bit)
end
go
select dbo.fnCheckIP('127.0.0.1')
select dbo.fnCheckIP('127.0.0.300')
出于好奇,你是否要在应用程序中验证IP地址,然后再将其插入数据库? – JohnB 2010-07-29 13:10:24
是的,我会的,但正如我在回答Josh K时所说的,其他软件(我们不开发)将访问此数据库,因此它必须足够强大。 – Shimrod 2010-07-29 13:15:49