SQL Server 存储过程T-SQL基础语法

一、定义变量及赋值

复制代码
--定义变量
declare @parameter_set varchar(20)
--赋值
set @parameter_set = 1;
select @parameter_set = '';
update Members set @parameter_set = Name where ID='';
--定义表变量
declare @tab table(Id varchar(36) not null,Name varchar(10) null)
--赋值
insert into @tab values('123','312');
--创建临时表,赋值同上
--# 表示局部 ## 表示全局
create table #table_1(
           --##table_1
    Id varchar(36) not null,
    Name varchar(10) null
)
--直接查询插入到临时表#table_2,无须创建
select * into #table_2 from Members
复制代码

二、条件、循环、分支语句、异常处理、事务

2.1 条件 if else

if(10>2)
    begin
        print('true');
    end
else
    begin
        print('false');
    end

2.2 循环 while

declare @num int
set @num=1 
while(@num<=10)
    begin
        print @num
    end

2.3 分支 case when then else

复制代码
declare @case_value int
declare @result varchar(10)
set @result = case
                when @case_value = 1 then '1'
                when @case_value = 2 then '2'
                when @case_value = 3 then '3'
                when @case_value = 4 then '4'
                else'0'
              end
print @result
复制代码

2.4 异常处理try catch

复制代码
begin try
    declare @try_int int;
    set @try_int = 1 / 0;
    print('1');
end try
begin catch
--这几个函数只能用在Catch里面!
    print(error_number());print(error_severity());
    print(error_state());print(error_procedure());
    print(error_line());print(error_message());
end catch
复制代码

2.5 事务 tran

复制代码
begin tran
    --执行业务逻辑,例如修改数据    
    if(@@ERROR <> 0) 
        begin
            --存在错误回滚
            rollback tran;
        end
commit tran
--最后提交
复制代码
posted @   浩叔  阅读(717)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示