1 ---查询当前数据库一共有多少张表 2 select COUNT(1) from sysobjects where xtype='U' 3 4 ---查询当前数据库有多少张视图 5 select COUNT(1) from sysobjects where xtype='V' 6 ---查询当前数据库 有多少个存储过程 7 select COUNT(1) from sysobjects where xtype='P' 8 -- row_number()函数用法 row_number() over (order by cloumn) from tableName 9 select ROW_NUMBER() over (order by cardNo ),* from T_ValueCard 10 11 select type from sysobjects group by type 12 -- 13 select * from sysobjects 14 15 --查询的时候临时生成自定义数据列 16 select 'Web' as SourceName,* from TM_Goods 17 --生成空列数据 18 select '' as SourceName, * from TM_Goods 19 --- 所查列的值出现特殊结果字符 给这个结果字符加单引号 如下所示的Sex字段 20 select top 20 ID, GuestName,MemNo,CardNo, [Identity], BagNo,BoxNo,case Sex when 'M' then '男' when 'F' then '女' end as Sex,Holes, 21 case [Status] when 1 then '已预约' when 2 then '已来场登记' when 3 then '已球场登记' when 4 then '已出发' 22 when 5 then '已离场' when 6 then '已结账' when 7 then '退回结账' when -1 then '已取消预约' when -2 then '取消登记' 23 when 0 then '未知' end as [Status], 24 StrategyCode, CreateTime,CheckinTime, Creator, CheckOutTime, CheckoutUser, 25 LastEditTime, LastEditor ,ExpiryDate, MainCardNo, 26 SalemanCode from Checkin 27 ---查询的时候如果结果里面包含空格或者特殊字符可以等量替换然后在进行查询 28 select * from TM_Goods where REPLACE(Name,' ','')=REPLACE('海立得 车载型空气净化机',' ','') 29 --查询当前数据库所有的表 30 select * from Dbserver..sysobjects where xtype='U' 31 --使用sp_addextendedproperty添加描述信息 32 -- 给表添加描述信息 table 33 EXECUTE sp_addextendedproperty N'MS_Description', '描述内容', N'user', N'dbo', N'table', N'表名', NULL, NULL 34 35 -- 给表中的列添加描述信息 column 36 EXECUTE sp_addextendedproperty N'MS_Description', '描述内容', N'user', N'dbo', N'table', N'表名', N'column', N'字段名' 37 --修改表中列的长度 38 alter table T_DataDictionary 39 alter column Value varchar(50) 40 --查询关键词带有空格符的数据 41 select * from TM_OrderDetail where REPLACE(Name,' ','')=REPLACE('迪斯尼 笑脸米奇丝绒毯',' ','') 42 43 --模糊查询关键词带有空格符的数据 44 --select * from TM_Goods where REPLACE(Name,' ','') like '%'+REPLACE('海立得 ',' ','')+'% 45 46 --条件区分大小写语法 47 select * from tablename where column1 collate Chinese_PRC_CS_AS= 'Xxxx' 48 select * from s where sn collate Chinese_PRC_CS_AS like 'L%' 49 --CI 指定不区分大小写,CS 指定区分大小写。 50 --AI 指定不区分重音,AS 指定区分重音。 51 --Omitted 指定不区分大小写,WS 指定区分大小写。 52 53 --区分大小写查询例子 54 select * from MemberEntity where MemNo collate Chinese_PRC_CS_AS= 'M_001' 55 --select * from MemberEntity where MemNo collate Chinese_PRC_CS_AS= 'm_001' 56 57 --触发器 58 if not exists (select * from sysobjects where id=OBJECT_ID('Student') and name='Student') 59 begin 60 create table Student --学生表 61 ( 62 StudentID int primary key, --学号 63 StudentName nvarchar(15) --姓名 64 ) 65 end 66 67 if not exists (select * from sysobjects where id=OBJECT_ID('BorrowRecord') and name='BorrowRecord') 68 begin 69 create table BorrowRecord --借书记录表 70 ( 71 RecordID int primary key, --流水号 72 StudentID int, --学号 73 OutTime datetime, --借出时间 74 ReturnDate datetime --归还时间 75 )
76 end
--为表添加描述信息
EXECUTE sp_addextendedproperty N'MS_Description', '借书记录表', N'BorrowRecord', N'dbo', N'table', N'表', NULL, NULL
--为字段a1添加描述信息
EXECUTE sp_addextendedproperty N'MS_Description', '学号', N'user', N'dbo', N'table', N'BorrowRecord', N'column', N'StudentID'
78 --创建触发器语法 79 create trigger trigger_name 80 on {table_name | view_name} 81 {for | After | Instead of } [ insert, update,delete ] 82 83 as sql_statement 84 85 --删除触发器 drop trigger trigger_name 86 --查看当前数据库的触发器 87 select * from sysobjects where type='TR' 88 --查看某个触发器 89 exec sp_helptext 'TStudent' 90 91 --触发器实例----触发器是属于隐式的 92 create trigger TStudent 93 on Student --在Student表中创建触发器 94 for Update --针对什么事件触发 95 as --时间触发后要做的事情 96 if update(StudentID) 97 begin 98 Update BorrowRecord 99 set StudentID=i.StudentID 100 from BorrowRecord br,Deleted d,Inserted i --Deleted和Inserted为临时虚拟表 101 where br.StudentID=d.StudentID 102 end 103 go
sql 中对列值(Code='023,033')进行逗号分割
1 -----------------------------------------split函数开始 2 SET ANSI_NULLS ON 3 GO 4 SET QUOTED_IDENTIFIER ON 5 GO 6 -- ============================================= 7 -- Author: wgx 8 -- Create date: 2010-09-28 9 -- Description: 实现split功能的函数 10 -- ============================================= 11 ALTER function [dbo].[F_Split](@SourceSql varchar(8000),@StrSeprate varchar(10)) 12 13 returns @temp table(a varchar(100)) 14 15 as 16 17 begin 18 declare @i int 19 20 set @SourceSql=rtrim(ltrim(@SourceSql)) 21 set @i=charindex(@StrSeprate,@SourceSql) 22 23 while @i>=1 24 25 begin 26 insert @temp values(left(@SourceSql,@i-1)) 27 set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i) 28 set @i=charindex(@StrSeprate,@SourceSql) 29 end 30 31 if @SourceSql<>'' 32 33 insert @temp values(@SourceSql) 34 return 35 end 36 -----------------------------------------split函数结束 37 --用法 38 declare @str1 varchar(8000) 39 select @str1 = StartID from T_TtimeCaddy where ID=111230 40 select * from dbo.F_Split(@str1,',')
split 分割函数(2):
1 SET ANSI_NULLS ON 2 GO 3 SET QUOTED_IDENTIFIER ON 4 GO 5 -- ============================================= 6 -- Author: wgx 7 -- Create date: <Create Date, ,> 8 -- Description: 实现表中列的值进行分割 9 --知识点如下: 10 -- 1.Left(原始字符串,位数): Left函数用来取字符串的前几位 11 -- Left('269,268,267,266',3) 结果:269 12 -- 2.CHARINDEX函数(字符,原始字符串): 取字符在字符串出现第一次的索引 13 -- CHARINDEX(',', '269,268,267,266') 结果:4 14 -- 3.STUFF(列名,开始位置,长度,替代字符串): STUFF()函数用于删除指定长度的字符,并可以在制定的起点处插入另一组字符 15 -- STUFF('269,268,267,266', 1, 4, '')结果: 268,267,266 16 -- ============================================= 17 ALTER FUNCTION [dbo].[F_Split] 18 ( 19 @Str varchar(8000) 20 ) 21 RETURNS @ReturnTable table( 22 Id int identity(1,1), 23 value varchar(50) 24 ) 25 AS 26 BEGIN 27 declare @pos int 28 set @pos=charindex(',',@str) 29 while @pos>0 30 begin 31 INSERT @ReturnTable(value) VALUES(LEFT(@str, @pos - 1)) 32 SELECT 33 @str = STUFF(@str, 1, @pos, ''), 34 @pos = CHARINDEX(',', @str) 35 end 36 IF @str >'' 37 insert @ReturnTable(value) values(@str) 38 return 39 END
用法:select * from F_Split('269,268,267,266',',')
分割后的效果:
1 alter table 需要建立外键的表 add constraint 外键名字 foreign key references 外键表(外键字段)
1 --返回上一语句受影响的行数 2 @@ROWCOUNT 3 --使用示例 4 update T_Round set IsBet=0 where ID=4508 5 if @@rowcount>0 6 begin 7 print '成功' 8 end 9 else 10 begin 11 print '失败' 12 end
1 --IsNull函数 使用指定的替换值替换 NULL。 2 --语法:ISNULL ( check_expression , replacement_value ) 3 select ISNULL(SubType,'0' )as 类型,* from T_Product where ID=703
1 --表总数 2 select Count(ID) from BillItem 3 --按年统计数据 4 select count(Price) as sumValue from BillItem where YEAR(CreateTime)=2013 5 select count(Price) as sumValue from BillItem where YEAR(CreateTime)=2014 6 select count(Price) as sumValue from BillItem where YEAR(CreateTime)=2015 7 --统计当前月的所有数据 8 select Count(*) from BillItem where MONTH(CreateTime)=12 9 --按年和月统计数据 10 select Count(*) from BillItem where YEAR(CreateTime)=2013 and MONTH(CreateTime)=12
使用sql自带的四舍五入函数Round(要转换的数据,保留的位数)
1 select TotalRent,ROUND(TotalRent,0) from TBL_CONTRACT_BasicInfo 第一个参数是我们要被操作的数据,第二个参数是设置我们四舍五入之后小数点后显示几位
case when 中null 判断:
1 select 2 a.IsCost, 3 case when a.IsCost is null then '未算' else '已算' end as IsCostStr, 4 b.FeeBalance, 5 case b.FeeBalance when 0 then '已缴' else '未缴' end IsPayState 6 from TBL_LeasebackContract_Details as a 7 left join TBL_Charge_CostingInfo as b on a.ID=b.ID 8 where 1=1
1 -----------------------------------------------------同步相同结构数据库的同一个表中的记录----------------------------------------------------- 2 --语法 3 insert into 数据库2.dbo.表1 select * from 数据库1.dbo.表1 4 5 --实例 6 insert into pms_common.dbo.TBL_Estate_BuildingInfomation 7 select * from gdjdb.dbo.TBL_Estate_BuildingInfomation 8 -----------------------------------------------------同步相同结构数据库的同一个表中的记录-----------------------------------------------------
1 --------------查询登陆大于等于1次的登陆用户的IP地址----------- 2 select IPAddress from SysLoginLog 3 group by IPAddress having count(1)>=1
---同一个表的俩字段,根据某个列值判断是否为空来付给同一张表中的另一列 select EndDate,StopDate,case when StopDate is not null then StopDate else EndDate end as NewEndDate from TBL_CONTRACT_BasicInfo
--循环更改图片路径 declare @id int,@url varchar(250) set @id=1; while(@id<22) begin set @url='temp/img'+CONVERT(varchar,@id)+'.jpg' --print @url update Shop_CompanyInfo set com_topcontpic=@url where com_id=@id set @id=@id+1; end go
行转列查询:
select T2.code,T2.nub from ( select ISNULL(SUM(上班次数), 0) as 上班, ISNULL(SUM(请假次数), 0) as 请假, ISNULL(SUM(出差次数), 0) as 出差, ISNULL(SUM(休假次数), 0) as 休假, ISNULL(day(dateadd(mm, 1, '2018-10-01 00:00:00.000') - day('2018-10-01 00:00:00.000')) - sum(请假次数 + 出差次数 + 休假次数), 0) as 未打卡 from View_AttendanceSummary where UserId =8 and SUBSTRING(考勤日, 1, 4) = 2018 and SUBSTRING(考勤日, 6, 2) =10 ) T1 UNPIVOT ( nub for code in(上班, 请假, 出差, 休假, 未打卡) ) T2
选中结果为行结果
转列:
select T2.code,T2.nub from ( select ISNULL(SUM(上班次数), 0) as 上班, ISNULL(SUM(请假次数), 0) as 请假, ISNULL(SUM(出差次数), 0) as 出差, ISNULL(SUM(休假次数), 0) as 休假, ISNULL(day(dateadd(mm, 1, '2018-10-01 00:00:00.000') - day('2018-10-01 00:00:00.000')) - sum(请假次数 + 出差次数 + 休假次数), 0) as 未打卡 from View_AttendanceSummary where UserId =8 and SUBSTRING(考勤日, 1, 4) = 2018 and SUBSTRING(考勤日, 6, 2) =10 ) T1 UNPIVOT ( nub for code in(上班, 请假, 出差, 休假, 未打卡) ) T2
列转行:
--将多列数据展示成一行 SELECT CAST(用户Id as varchar)+',' FROM DB_Participant where 督办事项Id=49 FOR XML PATH('') SELECT b.真实姓名+',' FROM DB_Participant as a left join SysUser as b on a.用户Id=b.Id where a.督办事项Id=49 FOR XML PATH('')
sqlserver -- 学习笔记(五)查询一天、一周、一个月记录(DateDiff 函数)
http://www.cnblogs.com/lmei/p/3946599.html