开始...结束 SQL Server 中的块:这段代码对吗? [英] Begin...End blocks in SQL Server: Is this code right?

查看:16
本文介绍了开始...结束 SQL Server 中的块:这段代码对吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想确认我没有在这里遗漏任何东西......所以请耐心等待.

I just want to verify that I'm not missing something here... so bear with me.

我正在重写很多旧的存储过程,并不断看到格式与此类似的 IF 语句:

I'm rewriting a lot of old stored procedures and keep seeing IF statements formatted similar to this:

begin
    if @someParameter <> 'ThisType'
    set @someCode = right(cast(@pYear as varchar(6)),2) + 'THIS'
end

所以 Begin...End 块只是包装(但不影响)IF 语句,对吗?这是 IF 的一些旧语法还是什么?

So the Begin...End block just wraps (but does not effect) the IF statement, right? Is this some older syntax for IF or something?

写这篇文章的人在这份工作之前没有很多 SQL 经验;他主要在 VB (pre-.NET) 中工作.也许这是其他语言的语法,所以他不小心这样写(习惯)?

The guy who wrote this didn't have a lot of SQL experience prior to this job; he worked mostly in VB (pre-.NET). Maybe this is syntax from some other language, so he accidentally wrote it this way (by habit)?

这是 SQL Server 2005(代码是为 SQL Server 2000 编写的),顺便说一句

This is SQL Server 2005 (code was written on/for SQL Server 2000), btw

就像我说的,我只是想把我的大脑围绕在这个意大利面条上.欢迎任何想法/评论/启发性见解

Like I said, I'm just trying to wrap my brain around this spaghetti. Any thoughts/comments/illuminating insights are welcome

谢谢

推荐答案

在 T-SQL 中,Begin 和 END 应该将 IF(或其他控制结构)的包含语句与正在执行的多个语句(如代码块)一起包装起来

In T-SQL Begin and END should wrap the contained statements of an IF (or other control structure) with multiple statements being executed (like a code block)

可行

if @someParameter <> 'ThisType'
    set @someCode = right(cast(@pYear as varchar(6)),2) + 'THIS'

也可以,但不是绝对必要

if @someParameter <> 'ThisType'
Begin
    set @someCode = right(cast(@pYear as varchar(6)),2) + 'THIS'
End

会按预期工作

if @someParameter <> 'ThisType'
Begin
    set @someCode = right(cast(@pYear as varchar(6)),2) + 'THIS'
    {...do other stuff}
End

不会按预期工作(如果您希望这两个语句仅在 IF 条件为我时执行)

Would not work as expected (if you expected the both statements to only execute if the IF condition is me)

if @someParameter <> 'ThisType'
    set @someCode = right(cast(@pYear as varchar(6)),2) + 'THIS'
    {...do other stuff}

没有语义价值

Begin --without wrapping control structure
    {...stuff}
End 

这篇关于开始...结束 SQL Server 中的块:这段代码对吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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