当前位置: 代码迷 >> Sql Server >> Mssql 中如何自动增加行
  详细解决方案

Mssql 中如何自动增加行

热度:81   发布时间:2016-04-27 10:55:11.0
Mssql 中怎么自动增加行
比如我有一行记录
姓名 号码开始 号码结束 
张三 1    1
李四 2 5
王二麻子 6 10

我想要创建一个这样的视图
张三 1
李四 2
李四 3
李四 4
李四 5
王二麻子 6
王二麻子 7
王二麻子 8
王二麻子 9
王二麻子 10
请问有什么办法可以做到



------解决方案--------------------
MASTER..SPT_VALUES
------解决方案--------------------
SQL code
------------------------------ 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 allselect '李四',2,5 union allselect '王二麻子',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'
  相关解决方案