Single line GO(Batch) statement giving error in SQ

2019-07-13 06:21发布

问题:

I have one question. I was creating below procedure temporary.

When I Execute it in below format it works fine:

CREATE PROCEDURE Get_TableList_By_Name
@Proc_Name VARCHAR(255)
AS
BEGIN
    SELECT * FROM sys.tables WHERE name LIKE '%' + @Proc_Name + '%'
END 
GO
EXEC Get_TableList_By_Name 'norway'
GO
DROP PROCEDURE Get_TableList_By_Name 
GO

But when I execute same SQL in below format it giving error saying: "Incorrect syntax near 'GO'."

CREATE PROCEDURE Get_TableList_By_Name @Proc_Name VARCHAR(255) AS BEGIN SELECT * FROM sys.tables WHERE name LIKE '%' + @Proc_Name + '%' END GO EXEC Get_TableList_By_Name 'norway' GO DROP PROCEDURE Get_TableList_By_Name GO

CREATE PROCEDURE Get_TableList_By_Name @Proc_Name VARCHAR(255) AS BEGIN SELECT * FROM sys.tables WHERE name LIKE '%' + @Proc_Name + '%' END GO 1 EXEC Get_TableList_By_Name 'norway' GO 1 DROP PROCEDURE Get_TableList_By_Name GO 1

How to write same SQL with GO statement in single line? Is it possible? If not then Why?

Thanks, Vishal

回答1:

From GO (Transact-SQL)

A Transact-SQL statement cannot occupy the same line as a GO command. However, the line can contain comments.

So Go needs to be on its own line, except for comments.



回答2:

'GO' is not a SQL command. It is a batch terminator recognized by tools like Query Analyzer, SSMS, SQLCMD, etc. These tools generally require the GO to be on a separate line and send the preceding SQL statements as a batch to SQL Server when the GO is encountered

GO Statement must be written in new line as it is not T-SQL command. T-SQL statement can not occupy the same line as GO. GO statement can contain comments.