日度归档:2019年8月28日

mssql sqlserver “查找临时表,如果存在则删除临时表”的方法分享


摘要:
下文讲述使用sql脚本检索临时表是否存在,及删除临时表的方法
实验环境:sql server 2008 R2


临时表是我们在复杂的sql脚本必须使用的一种数据缓存集,
合理的使用临时表可以加快数据的检索速度,
减少数据检索的次数,
从而使数据库运行更高效。

下文讲述,我们在使用临时表时,检查临时表是否存在及清除临时表的方法。

  ---例:检测临时表"maomao"是否存在,如果存在,则删除
 if exists(select * from tempdb..sysobjects where id=object_id('tempdb..#maomao'))  ---临时表检测
  begin  
    drop table #maomao   ---临时表删除
  end

mssql sqlserver 使用sql脚本导出表结构及表说明的方法分享


摘要:
下文举例讲述sqlserver中采用sql脚本输出表结构的方法,如下所示:
实验环境:sqlserver 2008 R2


    SELECT   a.id as [对象Id], 
      CASE WHEN a.colorder = 1 THEN d.name ELSE '' END AS [表名称], 
      CASE WHEN a.colorder = 1 THEN isnull(f.value, '') ELSE '' END AS [表备注], 
      a.colorder AS [字段顺序号], a.name AS [字段名称],
       CASE WHEN COLUMNPROPERTY(a.id, 
      a.name, 'IsIdentity') = 1 THEN '√' ELSE '' END AS [是否标识列], 
      CASE WHEN EXISTS
          (SELECT 1
         FROM dbo.sysindexes si INNER JOIN
               dbo.sysindexkeys sik ON si.id = sik.id AND si.indid = sik.indid INNER JOIN
               dbo.syscolumns sc ON sc.id = sik.id AND sc.colid = sik.colid INNER JOIN
               dbo.sysobjects so ON so.name = si.name AND so.xtype = 'PK'
         WHERE sc.id = a.id AND sc.colid = a.colid) THEN '√' ELSE '' END AS [是否主键], 
      b.name AS [字段类型], a.length AS [字段长度], COLUMNPROPERTY(a.id, a.name, 'PRECISION') 
      AS [字段精度], ISNULL(COLUMNPROPERTY(a.id, a.name, 'Scale'), 0) AS [字段小数位数], 
      CASE WHEN a.isnullable = 1 THEN '√' ELSE '' END AS [是否允许null], ISNULL(e.text, '') 
      AS [字段默认值], ISNULL(g.[value], '') AS [字段备注], d.crdate AS [对象创建时间], 
      CASE WHEN a.colorder = 1 THEN d.refdate ELSE NULL END AS [对象修改时间]
FROM dbo.syscolumns a LEFT OUTER JOIN
      dbo.systypes b ON a.xtype = b.xusertype INNER JOIN
      dbo.sysobjects d ON a.id = d.id AND d.xtype = 'U' AND 
      d.status >= 0 LEFT OUTER JOIN
      dbo.syscomments e ON a.cdefault = e.id LEFT OUTER JOIN
      sys.extended_properties g ON a.id = g.major_id AND a.colid = g.minor_id AND 
      g.name = 'MS_Description' LEFT OUTER JOIN
      sys.extended_properties f ON d.id = f.major_id AND f.minor_id = 0 AND 
      f.name = 'MS_Description'
ORDER BY d.name, [字段顺序号]
mssql_sqlserver_sql脚本导出表结构

mssql_sqlserver_sql脚本导出表结构

mssql sqlserver 如何将数据和sum结果一起显示呢?


摘要:
下文讲述sqlserver使用sql脚本在数据表后面加上一个sum合计列,如下所示:
实验环境:sql server 2008 R2

----基础数据准备
create table [maomao365.com]
(keyId int identity,
 info  nvarchar(30),
 qty  int)
 go
 insert into [maomao365.com]
(info,qty)values(N'sqlserver',18),
(N'sql爱好者',189),(N'sql教程',81),
(N'猫猫小屋',56)
go

select *,
sum(qty) over() as[附加sum] 
from [maomao365.com]
 
 go
 truncate table [maomao365.com]
 drop     table [maomao365.com]

mssql_sqlserver_数据表附加sum列的方法分享_9528

mssql_sqlserver_数据表附加sum列的方法分享_9528


相关阅读:
多列数据进行求和sum计算
sum使用if进行按条件汇总
sum函数计算后的结果中包含null的处理方法
sum计算个数的例子分享
sum求和函数简介
sum(1)、count(*) 效率对比分析
sum(1)、sum(2)、count(1)、count(8)、count(*)、统计函数应用区别简介
数据库中sum和count用法区别说明
sql脚本对数据表所有行和列值求和的方法