在 SQL 中使用 Go 执行动态查询。
在 SQL 中使用 Go 执行动态查询。
在执行上述查询时发生了错误消息。请告诉我如果你有解决方法的话。
错误消息:第4行附近有语法错误'go'。
注意:上面的创建和删除表的代码只是示例,我有一些其他带有'go'语句的动态查询。请不要给出这个答案。
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);
在使用动态T-SQL查询时,无法使用GO
,如所述。
由于您不想运行独立的SQL查询,正如您问题的第二部分所述,您可以通过将查询拆分为独立的批处理来解决这个问题。
您可以使用UDF将查询拆分为GO
。拆分后,执行分离的批处理。
但是,首先创建一个包含GO
的字符串,然后在几分钟后将其拆分,这并不自然。
在SQL中使用go执行动态查询的原因是为了将多个查询语句串联起来执行,但是go关键字在执行动态查询时会出现问题。解决方法是通过在动态查询语句中添加一行代码来替代go关键字的作用。具体的解决方法如下:
-- Your Script modified by adding a single line of code: DECLARE @Query nVarChar(MAX); -- I changed from VarChar to nVarChar - you should always use nVarChar for Dynamic SQL. SET @Query = ' create table ali(id decimal(10,0)); drop table ali; go create table ali(id decimal(10,0)); drop table ali; ' -- In case you have apostrophes in your script, you must escape them for the Exec() command. - 03/14/2013 - MCR. SET @Query = 'EXEC (''' + REPLACE(REPLACE(@Query, '''', ''''''), 'GO', '''); EXEC(''') + ''');' -- Just add this one line. PRINT @Query -- See the command used (will be truncated in Select/Print, but not when Executing). EXEC (@Query);
对于需要在动态查询中动态连接多个语句的情况,可以通过以下示例来解决:
-- Example of compiling and chaining multiple DDL statments from data in a table: -- DDL (Data Definition Language). -- These are statements used to create, alter, or drop data structures. -- They MUST be run in a single Batch. -- The "GO" keyword is a SSMS syntax for splitting up batches - it is not an SQL keyword. DECLARE @Statements TABLE ( DDL nVarChar(MAX) ) INSERT INTO @Statements (DDL) SELECT 'create table ali(id decimal(10,0)); drop table ali;' UNION ALL SELECT 'create table ali(id decimal(10,0)); drop table ali;' DECLARE @Query nVarChar(MAX) = '' SELECT @Query = @Query + 'EXEC(''' + REPLACE(DS.DDL, '''', '''''') + '''); ' FROM @Statements as DS -- In case you have apostrophes in your script, you must escape them for the Exec() command. - 03/14/2013 - MCR. PRINT @Query -- See the command used (will be truncated in Select/Print, but not when Executing). EXEC (@Query)
需要注意的是,以上解决方法仍然存在一些问题,比如在语句之间存在依赖关系的情况下,无法正确执行。解决这些问题可以通过在关键字go周围添加回车符/换行符来限制替换的范围。此外,使用第二个解决方法可以完全避免使用go关键字,并通过使用表来存储所有要运行的语句,以便捕获并记录错误信息。