Programing

SQL Server에서 Begin / End Blocks 및 Go 키워드는 언제 사용해야합니까?

lottogame 2020. 8. 20. 19:26
반응형

SQL Server에서 Begin / End Blocks 및 Go 키워드는 언제 사용해야합니까?


누군가 SQL Server에서 언제 어디서 사용 begin하고 end차단 해야하는지 알려줄 수 있습니까 ?
또한 Go키워드는 정확히 무엇을 합니까?


GO는 스크립트의 끝과 같습니다.

GO로 구분 된 여러 CREATE TABLE 문이있을 수 있습니다. 스크립트의 한 부분을 다른 부분과 분리하는 방법이지만 모두 한 블록에 제출합니다.


BEGIN과 END는 C / ++ / #, Java 등에서 {및}와 같습니다.

그들은 논리적 코드 블록을 묶었습니다. 저장 프로 시저의 시작과 끝 부분에 BEGIN과 END를 사용하는 경향이 있지만 꼭 필요한 것은 아닙니다. 필요한 곳은 for 루프, IF 문 등이며 한 단계 이상이 필요합니다.

IF EXISTS (SELECT * FROM my_table WHERE id = @id)
BEGIN
   INSERT INTO Log SELECT @id, 'deleted'
   DELETE my_table WHERE id = @id
END

둘 이상의 문에 걸쳐있는 블록을 만들려면 BEGIN ... END가 필요합니다. 따라서 IF 문의 하나의 'leg'에서 두 가지 작업을 수행하거나 WHILE 루프 본문에서 두 가지 이상의 작업을 수행하려면 해당 구문을 BEGIN ...으로 묶어야합니다. 종료.

GO 키워드는 SQL의 일부가 아닙니다. 쿼리 분석기에서 스크립트를 독립적으로 실행되는 "일괄 처리"로 나누는 데만 사용됩니다.


GO는 SQL Server의 키워드가 아닙니다. 배치 구분자입니다. GO는 문 배치를 끝냅니다. 이것은 SQLCMD와 같은 것을 사용할 때 특히 유용합니다. 명령 줄에 SQL 문을 입력한다고 상상해보십시오. 명령문을 끝낼 때마다 해당 작업이 실행되는 것을 원하지는 않으므로 SQL Server는 "GO"를 입력 할 때까지 아무 작업도 수행하지 않습니다.

마찬가지로 배치가 시작되기 전에 종종 일부 개체를 표시해야합니다. 예를 들어 데이터베이스를 만든 다음 쿼리한다고 가정 해 보겠습니다. 다음과 같이 쓸 수 없습니다.

CREATE DATABASE foo;
USE foo;
CREATE TABLE bar;

foo는 CREATE TABLE을 수행하는 배치에 대해 존재하지 않기 때문입니다. 다음을 수행해야합니다.

CREATE DATABASE foo;
GO
USE foo;
CREATE TABLE bar;

BEGIN과 END는 다른 사람들로부터 좋은 답변을 받았습니다.

Gary가 지적했듯이 GO는 isql, sqlcmd, 쿼리 분석기 및 SQL Server Management Studio와 같은 대부분의 Microsoft 제공 클라이언트 도구에서 사용되는 배치 구분 기호입니다. (적어도 일부 도구를 사용하면 배치 구분 기호를 변경할 수 있습니다. 배치 구분 기호를 변경하는 용도는 본 적이 없습니다.)

GO를 언제 사용해야하는지에 대한 질문에 답하려면 SQL을 배치로 분리해야하는시기를 알아야합니다.

일부 문은 배치의 첫 번째 문이어야합니다.

select 1
create procedure #Zero as
    return 0

SQL Server 2000에서 오류는 다음과 같습니다.

Msg 111, Level 15, State 1, Line 3
'CREATE PROCEDURE' must be the first statement in a query batch.
Msg 178, Level 15, State 1, Line 4
A RETURN statement with a return value cannot be used in this context.

SQL Server 2005에서는 오류가 덜 유용합니다.

Msg 178, Level 15, State 1, Procedure #Zero, Line 5
A RETURN statement with a return value cannot be used in this context.

So, use GO to separate statements that have to be the start of a batch from the statements that precede it in a script.

When running a script, many errors will cause execution of the batch to stop, but then the client will simply send the next batch, execution of the script will not stop. I often use this in testing. I will start the script with begin transaction and end with rollback, doing all the testing in the middle:

begin transaction
go
... test code here ...
go
rollback transaction

That way I always return to the starting state, even if an error happened in the test code, the begin and rollback transaction statements being part of a separate batches still happens. If they weren't in separate batches, then a syntax error would keep begin transaction from happening, since a batch is parsed as a unit. And a runtime error would keep the rollback from happening.

Also, if you are doing an install script, and have several batches in one file, an error in one batch will not keep the script from continuing to run, which may leave a mess. (Always backup before installing.)

Related to what Dave Markel pointed out, there are cases when parsing will fail because SQL Server is looking in the data dictionary for objects that are created earlier in the batch, but parsing can happen before any statements are run. Sometimes this is an issue, sometimes not. I can't come up with a good example. But if you ever get an 'X does not exist' error, when it plainly will exist by that statement break into batches.

And a final note. Transaction can span batches. (See above.) Variables do not span batches.

declare @i int
set @i = 0
go
print @i

Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@i".

GO ends a batch, you would only very rarely need to use it in code. Be aware that if you use it in a stored proc, no code after the GO will be executed when you execute the proc.

BEGIN and END are needed for any procedural type statements with multipe lines of code to process. You will need them for WHILE loops and cursors (which you will avoid if at all possible of course) and IF statements (well techincally you don't need them for an IF statment that only has one line of code, but it is easier to maintain the code if you always put them in after an IF). CASE statements also use an END but do not have a BEGIN.


After wrestling with this problem today my opinion is this: BEGIN...END brackets code just like {....} does in C languages, e.g. code blocks for if...else and loops

GO is (must be) used when succeeding statements rely on an object defined by a previous statement. USE database is a good example above, but the following will also bite you:

alter table foo add bar varchar(8);
-- if you don't put GO here then the following line will error as it doesn't know what bar is.
update foo set bar = 'bacon';
-- need a GO here to tell the interpreter to execute this statement, otherwise the Parser will lump it together with all successive statements.

It seems to me the problem is this: the SQL Server SQL Parser, unlike the Oracle one, is unable to realise that you're defining a new symbol on the first line and that it's ok to reference in the following lines. It doesn't "see" the symbol until it encounters a GO token which tells it to execute the preceding SQL since the last GO, at which point the symbol is applied to the database and becomes visible to the parser.

Why it doesn't just treat the semi-colon as a semantic break and apply statements individually I don't know and wish it would. Only bonus I can see is that you can put a print() statement just before the GO and if any of the statements fail the print won't execute. Lot of trouble for a minor gain though.

참고URL : https://stackoverflow.com/questions/1180279/when-do-i-need-to-use-begin-end-blocks-and-the-go-keyword-in-sql-server

반응형