原表结构
SELECT [show_id]
,[year]
,[n1]
,[n2]
,[n3]
,[n4]
,[n5]
FROM [datapass_db].[dbo].[test]
1:SQL2005中的列转行.
SELECT [show_id], mon, SubTotal
FROM [datapass_db].[dbo].[test] UNPIVOT
(SubTotal FOR mon IN
([n1], [n2], [n3],[n4],[n5])
)AS unpvt;
2:SQL 2000 中的列转行
declare @tmpsql varchar(8000)
declare @sql varchar(8000)
select @tmpsql = ''
select @tmpsql = @tmpsql + ' UNION ALL SELECT '
+' show_id,'
+' year ,'
+name +' as mon'
+' from dbo.test'
from syscolumns
where object_id('dbo.test')=id and left(name,1) = 'n'
select @tmpsql=stuff(@tmpsql,1,11,'')
select @sql = 'select * from ('+@tmpsql+') t where t.mon>0'
print @sql
exec (@sql)
付送:
1:查找,已知列的表名.
select syscolumns.name,sysobjects.name from syscolumns , sysobjects
where syscolumns.id = sysobjects.id and syscolumns.name='要查的列名'
2:找出在两个数据库中表名称在彼此数据库中不存在的表名称,字段.
SELECT accdb.table_name AS accdb_table_name,
accdb.columns_name AS accdb_columns_name,
accdb1.table_name AS accdb1_table_name,
accdb1.columns_name AS accdb1_columns_name
FROM (SELECT Accdb.dbo.sysobjects.name AS table_name,
Accdb.dbo.syscolumns.name AS columns_name
FROM Accdb.dbo.syscolumns INNER JOIN
Accdb.dbo.sysobjects ON
Accdb.dbo.syscolumns.id = Accdb.dbo.sysobjects.id
WHERE (NOT (Accdb.dbo.syscolumns.name LIKE '@%')) AND
(Accdb.dbo.sysobjects.xtype = 'U')) accdb LEFT OUTER JOIN
(SELECT sysobjects.name AS table_name,
syscolumns.name AS columns_name
FROM syscolumns INNER JOIN
sysobjects ON syscolumns.id = sysobjects.id
WHERE (NOT (syscolumns.name LIKE '@%')) AND (sysobjects.xtype = 'U'))
accdb1 ON accdb.columns_name = accdb1.columns_name AND
accdb.table_name = accdb1.table_name
WHERE (accdb1.table_name IS NULL) OR
(accdb1.columns_name IS NULL) order by accdb.table_name,accdb.columns_name
其中accdb1为旧库,accdb为新库。
不只能查出表不同, 还包括字段的