日期:2014-05-18 浏览次数:20864 次
CREATE TABLE [2012-03-14] ( ID INT NOT NULL, Con VARCHAR(100) NOT NULL ) INSERT INTO [2012-03-14] SELECT 1,'aa' UNION SELECT 2,'bb' UNION SELECT 3,'cc' UNION SELECT 138,'dd' CREATE TABLE [2012-03-15] ( ID INT NOT NULL, Con VARCHAR(100) NOT NULL ) INSERT INTO [2012-03-15] SELECT 1,'aa' UNION SELECT 2,'bb' UNION SELECT 3,'cc' UNION SELECT 138,'dd' DECLARE @Table TABLE(Id INT IDENTITY(1,1),TableName VARCHAR(100)) DECLARE @Total INT DECLARE @Line INT DECLARE @Sql VARCHAR(8000) DECLARE @TableName VARCHAR(100) SET @Line = 1 INSERT INTO @Table SELECT name FROM SYSOBJECTS WHERE name LIKE '20%' SELECT @Total = MAX(Id) FROM @Table IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'UV_ShowAllTable') BEGIN DROP VIEW UV_ShowAllTable END SET @Sql = 'CREATE VIEW UV_ShowAllTable AS ' WHILE @Line <= @Total BEGIN SELECT @TableName = TableName FROM @Table WHERE Id = @Line SET @Sql = @Sql + ' SELECT Id,Con,' + '''' + @TableName + '''' + ' AS Date FROM ' + '[' + @TableName + ']' IF @Line <> @Total BEGIN SET @Sql = @Sql + ' UNION ' END SET @Line = @Line + 1 END EXEC (@Sql) SELECT * FROM UV_ShowAllTable WHERE ID = 138 AND Date BETWEEN '2012-03-01' AND '2012-03-31'
------解决方案--------------------
--化解字符串不能超过8000的方法二 --常有人提到,用动态生成SQL语句的方法处理数据时,处理语句超长,无法处理的问题 --下面就讨论这个问题: --创建测试数据 if exists (select * from dbo.sysobjects where id = object_id(N '[tb] ') and OBJECTPROPERTY(id, N 'IsUserTable ') = 1) drop table [tb] GO create table tb(单位名称 varchar(10),日期 datetime,销售额 int) insert into tb select 'A单位 ', '2001-01-01 ',100 union all select 'B单位 ', '2001-01-02 ',101 union all select 'C单位 ', '2001-01-03 ',102 union all select 'D单位 ', '2001-01-04 ',103 union all select 'E单位 ', '2001-01-05 ',104 union all select 'F单位 ', '2001-01-06 ',105 union all select 'G单位 ', '2001-01-07 ',106 union all select 'H单位 ', '2001-01-08 ',107 union all select 'I单位 ', '2001-01-09 ',108 union all select 'J单位 ', '2001-01-11 ',109 /*要求结果 日期 A单位 B单位 C单位 D单位 E单位 F单位 G单位 H单位 I单位 J单位 ---------- ----- ----- ----- ----- ----- ----- ----- ----- ----- ------ 2001-01-01 100 0 0 0 0 0 0 0 0 0 2001-01-02 0 101 0 0 0 0 0 0 0 0 2001-01-03 0 0 102 0 0 0 0 0 0 0 2001-01-04 0 0 0 103 0 0 0 0 0 0 2001-01-05 0 0 0 0 104 0 0 0 0 0 2001-01-06 0 0 0 0 0 105 0 0 0 0 2001-01-07 0 0 0 0 0 0 106 0 0 0 2001-01-08 0 0 0 0 0 0 0 107 0 0 2001-01-09 0 0 0