SQL Server T—SQL 基本编程

本文详细介绍了SQL中的变量定义、赋值、打印操作,以及分支和循环语句的应用实例,适合初学者快速掌握基本的SQL编程技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一 定义变量

     declare   @变量名   数据类型

                       例:declare  @a  int              -- 变量名前必须有 @
二 赋值

     set     @变量名 = 值   

     select  @变量名 = 值                              -- 赋值不能单独执行,必须与定义变量一起选中执行

                     例:set @a=10

三 取值打印  

   select @变量名 ;  --打印在结果集中

    print @变量名 ;   --打印在消息框中

                    例:print @a;

 

、查汽车表中所有汽车的平均值并输出

1 declare @price decimal(10,4) 
2 
3 select @price = AVG(Price) from Car 
4 
5 print '所有汽车的平均价格为:'+cast(@price as varchar(20))
View Code


四 分支语句

if ... else          -- if后面没有小括号,花括号用begin end 替代
  

if  判断条件
     begin
            要执行的语句
      end
  else
      begin
            要执行的语句
      end

declare @a int;
declare @b int;

select @a = 1;
select @b =2;
 
if @a > @b 
 begin 
  select 'a比b大'
 end
else
 begin
   select'b比a大'
 end
View Code

 

五 循环语句
   while         -- 注意循环四要素:初始条件,循环条件,循环体,状态改变

         初始条件

while 循环条件 
begin
        循环体

        状态改变
end

declare @a int;

select @a = 1

while @ <=10;

begin
    
     select @a ;
     
      select @a = @a + 1;

end
View Code

 

转载于:https://www.cnblogs.com/Tanghongchang/p/6560154.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值