新建存储过程
数据库名-->可编程性-->存储过程-->右击编写存储过程脚本为drop和create到新建查询编辑器窗口
可参考:http://www.cnblogs.com/oneivan/archive/2012/01/13/2321254.html
CREATE PROCEDURE[dbo].[procedureName ]
---此处为默认参数,为外面传递过来的参数值
@Date datetime as
begin
---此处参数是过程中可能会使用到的参数
declare @Timedatetime;
set @Time= ‘2015-07-02’;
---select没有set效率高,没有涉及到表操作时,用set设值
end;
调试存储过程
对於单个变量-->print @sth对于整个表select*from tableName
保存存储过程
撤销注释掉的代码运行下存储过程,成功则可在刷新后的存储过程目录下找到
调用存储过程
不用exec调用存储过程
create table()..
go --go表示要开始下一个事务了
procName --这里直接使用存储过程名字就是调用了
一定要使用exec调用存储过程
create table()
exec procName--不是作为这个事务的第一句开始的所以要带上exec
无参数
exec procName
有输出参数
exec procName参数,参数output
(参考 http://zhidao.baidu.com/question/171306193.html)
创建游标
声明一个游标,查询满足条件的数据
declare @A varchar(32)
declare CursorName cursor for
select A from tableName where sth--查询条件
打开游标
open CursorName;
fetch next
from
CursorName
into
@A --声明变量,用于读取游标中的值declare@sthint
循环读取
while @@FETCH_STATUS<> -1
begin
此处写入sql语句
fetch next
from
CursorName
into
@A
end;
关闭游标
close customerCursor;
删除游标
deallocate customerCursor;
创建临时表
一次性插入全部内容,每次输入的值一一对应
OBJECT_ID就是根据对象名称返回该对象的id,能够判断是否创建了临时表,#temptable为临时表的名称
if OBJECT_ID('tempdb..#temptable')isnotnull
临时表存在,删除临时表
drop table#temptable
创建临时表
create table#temptable(Aint,Bvarchar(30),Cnumeric(12,2),Dnumeric(12,2),Enumeric(12,2))
插入临时表
insert into#temptable values(@1,@2,@3,@4,@5+@6)
--- 将临时表数据导入到数据库中某表中
insert into tableName(element1,element2,element3,element4,element5)
select
排名,根据p.D排序,若p.D同则依据p.E排
ROW_NUMBER()OVER(orderbyp.Ddesc,p.Edesc)asranking,
如果p.A为空则p.A值设为0
isnull(p.A,0),
p.B,
p.C,
p.D
from #temptablep
order byranking
if OBJECT_ID('tempdb..#temptable')isnotnull
drop table#temptable
分多步插入临时表中的值
插入AB值
insert #temptable(A,B)
select
关键词distinct用于返回唯一不同的值
distinct
A1.D,
A2.ID
from
table1 A1, table2A2
where sth
插入C值
update #temptable
set C=(
select isnull(sum(P.CloseIncome-P.OpenCost-P.OpenCharge-P.CloseCharge), 0)
from HistoryPositionP
where #temptable.CustomerID=P.CustomerID
and P.PositionTime>=@startTime
and P.PositionTime<@endTime
and P.ModifyState= 1
)
日期、时间、星期
初始日期
declare @Timedatetime;
declare @weekDayint;
declare @hour int
declare @TradeDate date,
日期所在的周一日期
declare @mondayDatedatetime;
日期当前的小时数
select @hour=datepart(HOUR,@Date)--获取小时数
获取yyyy-MM-dd
将变量设置成date即可
去掉时分秒
保留日期12am为:00:00
set @Date= convert(char(10),@Date,20);
日期加上个小时
set @Time= dateadd(hh, 1,convert(char(10),@Date, 120));
--返回~7,以此表示星期日、星期一...星期六
set @weekDay= datepart(weekday,@Date);
----判断是否为周日
if(@weekDay=1)
begin
set @weekDay= @weekDay+ 7;
end;
set @mondayDate= dateadd(day, 2-@weekDay,@Date);--获取@Date所在的周一
若@mondayDate=dateadd(day,2-datepart(weekday,@Date))当@Date为周日时,@mondayDate为@Date的后一天,出错
nolock不加锁
若此选项被选中时,SQL Server 在读取或修改数据时不加任何锁。 在这种情况下,用户有可能读取到未完成事务(Uncommited Transaction)或回滚(Roll Back)中的数据, 即所谓的“脏数据”。
select * from table1 c with(nolock),table2 m with(nolock) where c.MediacyID=m.ID
and (
c.MemberID = @memberID or
c.MemberID in (select ID from Member with(nolock) where ParentMemberID = @memberID)
)