Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Dynamic Query with go in sql

DECLARE @script VARCHAR(MAX); SET @script =      '     create table ali(id decimal(10,0));     drop table ali;     go     create table ali(id decimal(10,0));     drop table ali;     '  EXEC (@script); 

Error message occured when execute above query. Please tell me if you have an idea for resolve this.

Msg 102, Level 15, State 1, Line 4 Incorrect syntax near 'go'.

Note : the above code for create and drop created table is just for example, i have some other dynamic queries with go statement. Please do not give this answer.

DECLARE @script   VARCHAR(MAX),         @script1  VARCHAR(MAX); SET @script =      '     create table ali(id decimal(10,0));     drop table ali;     '; SET @script1 =      '     create table ali(id decimal(10,0));     drop table ali;     '; EXEC (@script); EXEC (@script1); 
like image 628
Husain Sanwerwala Avatar asked Jan 23 '13 05:01

Husain Sanwerwala


People also ask

Can you use go in dynamic SQL?

You simply can't use GO in a dynamic T-SQL query, as stated by @mellamokb. Since you don't want to run the separate SQL-queries, as stated in the second part of your question, you might get away by splitting the query in separate batches yourself. You could split the query on GO using a UDF.

How do I run a dynamic SQL query?

Executing dynamic SQL using sp_executesql sp_executesql is an extended stored procedure that can be used to execute dynamic SQL statements in SQL Server. we need to pass the SQL statement and definition of the parameters used in the SQL statement and finally set the values to the parameters used in the query.

How do you pass dynamic parameters in SQL query?

Executing dynamic SQL queries Dynamic SQL queries are those built at runtime based on one or more variable values. To execute those queries, we must concatenate them into one SQL statement and pass them as a parameter to the sp_executesql stored procedure.

Can we use CTE in dynamic SQL?

They allow to encapsulate the SQL query and reuse result recursively as a data source in the main query or in another CTE within one statement. In this article I'll illustrate how to use CTEs using an example of dynamic query which counts records from one table joined with second table used to limit the result set.


1 Answers

GO is actually not valid T-SQL:

GO is not a Transact-SQL statement; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor.

You will have to remove instances of GO in your dynamic SQL, or use one of the tools mentioned on the article (such as osql from the command-line). Your query should still work with all instances of GO removed from the dynamic SQL.

like image 135
mellamokb Avatar answered Oct 10 '22 11:10

mellamokb