读书人

查看范围区间不存在的数字,该怎么处理

发布时间: 2013-10-21 17:02:52 作者: rapoo

查看范围区间不存在的数字
要求取1至 100之间数据库中不包含的值

数据库表T结构(值为用户添加的 不断增加的)
VALUE
22
33
99
5


也就是说取1——100之间 除数据库中值以外的所有数字 请问这个要怎样编写语句
[解决办法]
select number from master..spt_values
left join T on number=T.[value]
where type='p' and number<100 and T.[value] is null
[解决办法]

select number
from mster..spt_values s left join t where s.number=t.value and type='p'
where t.value is null

[解决办法]
修改下,把最小值最大值加上。。。


declare @i int
declare @n int
declare @min int
declare @max int


set @i=0--生成数据最小值
set @n=10000--生成数据最大值

set @min=5000--查询范围最小值
set @max=10000--查询范围最大值


CREATE TABLE #t(
[ID] [int] IDENTITY(1,1) NOT NULL,
[number] [int] NULL

)
CREATE TABLE #y(
[ID] [int] IDENTITY(1,1) NOT NULL,
[number] [int] NULL

)
---插入测试数据
insert into #t
select 1 union all
select 2 union all
select 3 union all
select 4

while (@i<=@n)
begin
insert into #y ([number]) values(@i)
set @i=@i+1
end


---查询测试结果
select y.number from #y y
left join #t T on y.number=T.[number]
where y.number>=@min and y.number<=@max and T.[number] is null

drop table #t
drop table #y





[解决办法]
引用:
引用:

select number from master..spt_values
left join T on number=T.[value]
where type='p' and number<100 and T.[value] is null

如果范围超过 2498呢
比如 5000——10000之间 数据库中以外的所有数字
--自己创建一个数字辅助表代替master..spt_values


IF OBJECT_ID('dbo.Nums') IS NOT NULL
DROP TABLE dbo.Nums;
GO
CREATE TABLE dbo.Nums(n INT NOT NULL PRIMARY KEY);
DECLARE @max AS INT, @rc AS INT;
SET @max = 1000000;
SET @rc = 1;

INSERT INTO Nums VALUES(1);
WHILE @rc * 2 <= @max
BEGIN
INSERT INTO dbo.Nums SELECT n + @rc FROM dbo.Nums;
SET @rc = @rc * 2;
END

INSERT INTO dbo.Nums
SELECT n + @rc FROM dbo.Nums WHERE n + @rc <= @max;
GO

读书人网 >SQL Server

热点推荐