基本的声明,复制,打印操作
declare,set,select,update
declare @newDeptID char(6),@className char(20)
update TB_Class
set @newDeptID = DeptID*2
where ClassID like '04%%%%' AND TeacherID ='T080002'
select @className=ClassName
from TB_Class
where ClassID='040201'
select @newDeptID,@className
打印记录数目
declare @rows int
set @rows =(select COUNT(*) from TB_Class)
select @rows
全局变量
SQL Server 的全局变量是由服务器而不是单个程序所定义的,可以在所有程序中使用,全局变量通常存储一些,配置定值和统计数据。
/*迄今为止试图登陆server的用户数*/
select getdate() as '当前时间',
@@connections as '试图登陆的用户数'
while使用
1-100的加法
declare @sum int,@cnt int
set @cnt=1
set @sum=0
while @cnt<=100
begin
set @sum=@sum+@cnt
set @cnt=@cnt+1
end
select @sum
内嵌表值自定义函数
不需要begin end,返回select 查询集
ALTER function [dbo].[func1](@StuName char(8))
returns table
as
return (select Enrollyear,gradYear
from TB_Student
where @StuName=StuName
)
ssms会自动在该部分前添加
USE [DB_TeachingMS]
GO
/****** Object: UserDefinedFunction [dbo].[func1] Script Date: 2020/3/30 14:08:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
调用
select * from dbo.func1('任正非')
标量值自定义函数
日期转换函数:2011-8-5–>3Q2011
create function DateQuarter(@dqdate datetime)
returns char(6)
as
begin
return(datename(q,@dqdate)+'Q'+datetime(yyyy,@dqdate))
end