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