Hus*_*ala 23 sql sql-server sql-server-2008
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);
Run Code Online (Sandbox Code Playgroud)
执行上述查询时出现错误消息.请告诉我你是否有解决这个问题的想法.
消息102,级别15,状态1,行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);
Run Code Online (Sandbox Code Playgroud)
Mik*_*Vee 11
我想这里的每个人都挂了"GO"关键字.
解:
--Your Script modified by adding a single line of code:
DECLARE @script nVarChar(MAX);--I changed from VarChar to nVarChar - you should always use nVarChar for Dynamic SQL.
SET @script =
'
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 @script = 'EXEC (''' + REPLACE(REPLACE(@script, '''', ''''''), 'GO', '''); EXEC(''') + ''');'--Just add this one line.
PRINT @script --See the command used (will be truncated in Select/Print, but not when Executing).
EXEC (@script);
Run Code Online (Sandbox Code Playgroud)
对于那些寻找动态连接表中多个语句的解决方案的人:
--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 @DDL_Statements TABLE
(
DDL nVarChar(MAX)
)
INSERT INTO @DDL_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 @SqlCommand nVarChar(MAX) = ''
SELECT @SqlCommand = @SqlCommand + 'EXEC(''' + REPLACE(DS.DDL, '''', '''''') + '''); '
FROM @DDL_Statements as DS --In case you have apostrophes in your script, you must escape them for the Exec() command. - 03/14/2013 - MCR.
PRINT @SqlCommand --See the command used (will be truncated in Select/Print, but not when Executing).
EXEC (@SqlCommand)
Run Code Online (Sandbox Code Playgroud)
您根本无法GO在动态T-SQL查询中使用,如@mellamokb所述.
由于您不想运行单独的SQL查询(如问题的第二部分所述),因此您可能会自行分开查询.
但是,首先GO在其中创建一个字符串,然后在片刻之后将其分开,这感觉并不自然.