SQL学习--



select * from [dbo].[Table_users]
declare @name nvarchar(40)
set @name='离开'
print'@name'
go


--declare 用于声明 @变量标示符 set 赋值标示
declare @age int
set @age=21
declare @name nvarchar(40)
set @name='离开'
print'@name'
select @age,@name
go


--将姓名分开
select LEFT(userName,1) as 姓, right(userName,2) as 名 from [dbo].[Table_users]
go


--left于用从左边截取字符left(@name,6)如 截取6个,right从右边
declare @name nvarchar(40)
set @name='你是哪个地方的呀'
select right(@name,3)
go


--union(联盟的意思)将行数连在一起
--convert强制转换 getdate获取当前时间
select 'ansi:',CONVERT(varchar(30),GETDATE(),102)as style 
union
select 'Japanse',convert(varchar(30),getdate(),111)as style
union
select 'asdsd',convert(varchar(30),getdate(),113)as style
go


--随机函数rand (*10)是取值的范围
declare @number int
set @number=RAND()*50
select @number
go


--查询当前时间select getdate()
select getdate()
go


--varchar用于计算时会自动转换为int类型
declare @a varchar(10)
declare @b int
set @a='101'
set @b=10 --convert(varchar,@b)转换为varchar类型
select @a+@b  --select @a+convert(varchar,@b)
go


--查询年份 Month 月份 天数 day
select Year(getdate())
go


-- 月数 天数
select DATEDIFF(day,'2016-4-28',getdate())


select DATEDIFF(month,'2015-5-20',GETDATE())


go


--if语句的应用


declare @score decimal
set @score=50+rand()*50
if(@score<60) print'不及格' else print '及格'
go


declare @score decimal
set @score=50+rand()*50
if(@score>80) 
begin
print'良好' print'良好'
end
else print '及格'
go


--case when 条件表达式 then 输出相对应的值 else '输出值' end
--case如switch  when如case else如dufault end结束
declare @score int
set @score=(50+rand()*50)/10
select case @score when 5 then '不及格'
when 6 then '及格'
when 7 then '良好'
else '优秀'
end
go



在做Sql Server开发的时候有时需要获取表中今天、昨天、本周、上周、本月、上月等数据,这时候就需要使用DATEDIFF()函数及GetDate()函数了。
DATEDIFF ( datepart , startdate , enddate )
释义:计算时间差
datepare值:year | quarter | month | week | day | hour | minute | second | millisecond
startdate:开始日期
enddate :结束日期
GetDate()
释义:获取当前的系统日期

下面例子中表名为tablename,条件字段名为inputdate
查询今天

SELECT * FROM tablename where DATEDIFF(day,inputdate,GETDATE())=0
查询昨天

SELECT * FROM tablename where DATEDIFF(day,inputdate,GETDATE())=1
查询本周

SELECT * FROM tablename where datediff(week,inputdate,getdate())=0
查询上周

SELECT * FROM tablename where datediff(week,inputdate,getdate())=1
查询本月

SELECT * FROM tablename where DATEDIFF(month,inputdate,GETDATE())=0
查询上月

SELECT * FROM tablename where DATEDIFF(month,inputdate,GETDATE())=1









 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值