1 先举个例子

Code
use myshop
declare @ident int
insert into orders
(customerid,orderdate)
values
(25,dateadd(day,-1,getdate()))--当前时间减去1天,就是昨天
select @ident = @@identity
insert into details
(orderid,productid,unitprice,quantity)
values
(@ident,1,50,25)
select 'the orderid of the inserted row is' + convert(varchar(8),@ident)
把数据插入定单表,得到新插入的记录的id然后插入定单明细表
2 定义变量给变量赋值
declare @myval int;
set @myval = 10;
set @myval1 = @myval2*12;
--下面语句是在查询中赋值变量
select @myval = max(id)+1 form mytable
3 if和else

Code
use xland
if not exists(select id from mytable)
print '暂时没有数据'
else
print cast(@@rowcount as varchar)+'被检索到'
上面语句执行结果是 0行被检索到
4 begin和end
如果条件内部要跟代码块(多条语句)
就要用到begin和end
5 case语句
第一种case语句

Code
use AdventureWorks
select SalesOrderID ,Position = Case SalesOrderID%10
when 1 then 'First'
when 2 then 'Second'
when 3 then 'third'
else 'some thing else'
end
from Sales.SalesOrderHeader
第二种case语句

Code
use AdventureWorks
select SalesOrderID ,Position = Case
when SalesOrderID%10 = 1 then 'First'
when SalesOrderID%10 = 2 then 'Second'
when SalesOrderID%10 = 3 then 'third'
else 'some thing else'
end
from Sales.SalesOrderHeader
第一种CASE when子句中可以跟表达式
第二种case when子句中表达式要返回true 或者false
当前面的条件和后面的条件同时满足时
按前面的条件处理,不需要break语句
6 循环语句
while 1=1
begin
waitfor time '01:00'
update mytable set num = 12 where id = 13
end
上面语句是在每天凌晨1点执行指定的操作
while允许break和continue的存在

Code
use xland
if not exists(select id from mytable)
print '没?有?检?索?到?数?据?'
else
begin
select id from mytable
print cast(@@rowcount as varchar)+'行?被?检?索?到?'
end
上面语句执行结果是:2行被检索到
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统