一、insert into:
方法1:inset table_name(col_name1,col_name2) into value(value1,value2)(sql server中不支持value,只支持下面的values关键字)
方法1.1:inset table_name(col_name1,col_name2) into values (val1,val2),(val3,val4)
方法1.2:inset table_name into value(value1,value2,values3......)
ps:对表插入所有对应的数据,要注意的是插入的顺序
方法2:insert table_name1(col_name1,col_name2) into select col_name1,col_name2 from table_name2 where .......
方法2.1:insert table_name1 into select col_name1,col_name2...... from table_name2 where .......
ps:注意插入的顺序
二、update 语句
update......set 语句
update table_name set col_name1='val1',col_name2='val2' where ......
三、T-SQL编程-批量
1、declare 声明与初始化
declare @sum int(变量声明)
也可以声明后初始化,如
declare @sum int=1
2、赋值语句 select与set
set @sum=0
select @sum=0
这两个都可以这样进行简单的赋值,其中select赋值还可以这样从其他表中选取赋值
select @sum=id from table_name where......
ps:用select语句进行这种行为的赋值时,值得注意的是!必须加入类似where这种条件语句。
否则得到的值会是查询到的最后一个值!
使用select语句赋值时,一定要记住变量赋的值取决于select语句查询的结果
3、打印语句print与select
print @sum;
select语句不仅可以用来赋值,还可以用来打印,如
select @sum;
其中select语句打印出来的结果是以表格的形式呈现
4、语句case的使用
使用1(简单case函数):当要与某个词或者某个数字的匹配时,可以先用变量储存要匹配的值,再输出
declare @mark varchar(20)
declare @output varchar(20)
select @mark=name from table_name where ......
select @outpue=
case @mark
when "a" then "Apple"
when "b" then "banana"
else "cat"
end
ps:@mark的值匹配到a时,则返回Apple;匹配到b时,则返回banana;否则返回cat
使用2(搜索case函数):当搜索或者要与某个范围的数值匹配时
select @output=
case
when (a-b)>2 then "大于2"
when (a-b)>3 then "大于3"
else "小于2"
end
ps:当a-b大于2时,返回“大于2”,并且赋值给@output。
值得注意的是:case搜索匹配到第一个符合的内容后,后面的case语句就会给忽略。如上面的例子,你永远只能得到第一个结果
四、关于代码块
begin
......
end
这相当于一个中括号{},如
在其它语言中,js,c++等if语句是这样的:
if(条件语句){
执行语句;
}
sql中是这样的:
if(条件语句)
begin
执行语句
end
五、存储过程
1.创建存储(不接收参数):
create proc gift(存储名称)
as
begin
select col_name1,col_name2 from table_name
end
执行语句:exec gift
2.创建存储(接受参数)
create proc gift(存储名称) @x varchar(20)
as
begin
if exists(select id from table_name where id=@x)
begin
delete from table_name where id=@x
end
end
执行语句:exec gift '1'
编译过程为:如果表中存在id为1的,则删除col_name
3.带输出参数的存储过程
详情请看blog
4.修改存储
alter proc gift(存储名称) @y varchar(30)
as
begin
if exists(select id from table_name where id=@x)
begin
delete from col_name where id=@x
end
end
5.删除存储
drop proc gift(存储名称)
6.查看存储
exec sp_helptext gift
exec sp_depends gift
exec sp_help gift
......
查看存储,可以使用sp_helptext、sp_depends、sp_help等系统存储过程来查看
存储过程的不同信息。
六、触发器
1、after触发器
create trigger gift(触发器名称) on table_name
after update(正在进行的操作)
as
begin
delete from table_name where...
end
当对table_name表进行更新,更新之后,会执行删除该表的某些记录(where...)
2.instead of触发器
instead of update(正在进行的操作)
as
begin
delete from table_name where...
end
当对table_name表进行更新,更新时,会执行删除该表的某些记录(where...)来
替代更新update操作(即update不执行)