日期:2014-05-17 浏览次数:20762 次
----------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2012-09-28 17:16:37
-- Version:
-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86)
-- Apr 22 2011 11:57:00
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)
--
----------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([姓名] varchar(8),[号码开始] int,[号码结束] int)
insert [tb]
select '张三',1,1 union all
select '李四',2,5 union all
select '王二麻子',6,10
--------------开始查询--------------------------
select a.姓名,b.number from tb a, master..spt_values b where number between 号码开始 and 号码结束 and type='p'
----------------结果----------------------------
/* 姓名 number
-------- -----------
张三 1
李四 2
李四 3
李四 4
李四 5
王二麻子 6
王二麻子 7
王二麻子 8
王二麻子 9
王二麻子 10
(10 行受影响)
*/
------解决方案--------------------
DECLARE @t TABLE(n VARCHAR(10),s INT,e INT);
INSERT INTO @t SELECT '张',1,1 UNION ALL SELECT '李',2,5 UNION ALL SELECT '王',6,10;
SELECT a.n,b.number FROM @t a JOIN master..spt_values b ON b.number BETWEEN a.s AND a.e
WHERE b.type='p'