只要花一点点时间学习下,就能用存储过程实现很复杂的功能,可以少写很多代码。
为了方便说明,数据库使用SQL Server的示例数据库,Northwind和pubs,如果SQL Server中没有的话,可以按下面的方法安装
1,下载SQL2000SampleDb.msi,下载地址是:
http://www.microsoft.com/downloads/details.aspx?FamilyId=06616212-0356-46A0-8DA2-EEBC53A68034&displaylang=en
2,安装后,到默认目录C:\SQL Server 2000 Sample Databases 有instnwnd.sql ,instpubs.sql两个文件
3,在sql server中运行这两个sql 就可以创建你Northwind和pubs数据库。
下面开始学T-SQL的语法
一.注释
-- 单行注释,从这到本行结束为注释,类似C++,c#中//
/* … */ 多行注释,类似C++,C#中/* … */
二.变量(int, smallint, tinyint, decimal,float,real, money ,smallmoney, text ,image, char, varchar。。。。。。)
语法:
DECLARE
{
{@local_variable data_type}
} [,...n]
例如:
declare @ID int --申明一个名为@ID的变量,类型为int型
三.在SQL Server窗口中打印出变量的值
语法:
PRINT 'any ASCII text' | @local_variable | @@FUNCTION | string_expr
四.变量赋值
例如:
--从数据表中取出第一行数据的ID,赋值给变量@id,然后打印出来
Declare @ID int
Set @ID = (select top(1) categoryID from categories)
Print @ID
在SQL中,我们不能像代码那样直接给变量赋值,例如@id = 1,如果要达到这样的功能,可以这样写:
Declare @ID int
Set @ID = (select 1) -- 类似 @ID=1
Select @id=1 -- 类似 @ID=1
Print @ID
五.变量运算(+,-,*,/,……)
以下必要时候省略变量申明
Set @ID = (select 1+5) --类似 @ID=1+5
Set @ID=(select 1-@ID) --类似 @ID=1-@ID
六.比较操作符
• > (greater than).
• < (less than).
• = (equals).
• <= (less than or equal to).
• >= (greater than or equal to).
• != (not equal to).
• <> (not equal to).
• ! < (not less than).
• !> (not greater than).
没什么说的
七.语句块:Begin … end
将多条语句作为一个块,类似与C++,C#中的{ }
例如:
Begin
Set @ID1 = (select 1)
Set @ID2 = (select 2)
End
八.If, if…else…
语法:
IF Boolean_expression
{sql_statement | statement_block}
[ELSE
{sql_statement | statement_block}]
例如:
If @id is not null
Print ‘@id is not null
if @ID = 1
begin
Set @ID = (select 1 + 1)
end
else
begin
set @ID=(select 1+2)
end
上面的例子用到了比较操作符,语句块,和IF的语法。
九.执行其他存储过程 EXEC
例如
EXEC dbo.[Sales by Year] @Beginning_Date=’1/01/90’, @Ending_Date=’1/01/08’
十.事务
语法:
BEGIN TRAN[SACTION] [transaction_name | @tran_name_variable]
例如
BEGIN TRAN
-- 做某些操作,例如Insert into …
if @@error <> 0
BEGIN
ROLLBACK TRAN
END
else
BEGIN
COMMIT TRAN
END
本篇文章来源于 黑客基地
相关资源:敏捷开发V1.0.pptx