在 T-SQL 中使用类似 Switch 的逻辑 [英] using Switch like logic in T-SQL

查看:24
本文介绍了在 T-SQL 中使用类似 Switch 的逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来像一个 noob T-SQL 问题,但我想在存储过程中像逻辑一样切换,我认为使用 CASE 将是使用类似

This looks like a noob T-SQL question but I want do switch like logic in a stored procedure and I was thinking that using a CASE would be the way to do this with something like

 SELECT CASE @Type
        WHEN 1 THEN
            INSERT INTO dbo.Credit (
                CompanyName,
                PhoneNumber,
                City,
                State
            ) VALUES ( 
                @CompanyName,
                @PhoneNumber,
                @City,
                @State) 
        WHEN 2 THEN  
            INSERT INTO dbo.Debit (
                CompanyName,
                PhoneNumber,
                City,
                State
            ) VALUES ( 
                @CompanyName,
                @PhoneNumber,
                @City,
                @State) 
        WHEN 3 THEN  
            --ETC
     END    

但我不断收到错误消息,是系统税错误还是我正在吃午饭?

but I keep getting errors, is there just a systax error or is what I'm doing out to lunch?

推荐答案

你需要使用If/Else If结构,像这样:

You need to use If/Else If structure, like this:

If @Type = 1
    Begin
        INSERT INTO dbo.Credit (
                CompanyName,
                PhoneNumber,
                City,
                State
        ) VALUES ( 
                @CompanyName,
                @PhoneNumber,
                @City,
                @State) 
    End
Else If @Type = 2
    Begin
        INSERT INTO dbo.Debit (
                CompanyName,
                PhoneNumber,
                City,
                State
        ) VALUES ( 
                @CompanyName,
                @PhoneNumber,
                @City,
                @State) 
    End
Else If @Type = 3
    Begin
        --ETC
    END

这篇关于在 T-SQL 中使用类似 Switch 的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆