T-SQL Syntax error

Vijay Kumar 1,996 Reputation points
2023-05-22T04:07:40.8666667+00:00

Hi Team,

I am working on dynamically restore DB.

As part of this i have created store procedure.

While running getting below syntax error:

Msg 102, Level 15, State 1, Line 12

Incorrect syntax near 'dba_db'.

Msg 132, Level 15, State 1, Line 13

The label 'L' has already been declared. Label names must be unique within a query batch or stored procedure.

Msg 132, Level 15, State 1, Line 14

The label 'L' has already been declared. Label names must be unique within a query batch or stored procedure.

Msg 132, Level 15, State 1, Line 15

The label 'L' has already been declared. Label names must be unique within a query batch or stored procedure.

Msg 132, Level 15, State 1, Line 16

The label 'L' has already been declared. Label names must be unique within a query batch or stored procedure.

Msg 132, Level 15, State 1, Line 17

The label 'L' has already been declared. Label names must be unique within a query batch or stored procedure.

Msg 132, Level 15, State 1, Line 18

	DECLARE @backup_files varchar(8000)
exec ABC.dbo.pr_RESTORE_STRING_FOLDER '\\1.2.3.4\dba\FULL\', 'dba_db', @backup_files OUTPUT


DECLARE @SQL VARCHAR(8000);

SET @SQL = @backup_files + CHAR(10) + 'WITH
	
	
	MOVE 'dba_db' TO 'L:\DATA\CAERPT1D\dba_db_NEW\dba_db.mdf' ,
	MOVE 'dba_db_log' TO 'L:\LOG\CAERPT1D\dba_db_NEW\dba_db_log.ldf' ,
	MOVE 'dba_db_FG_IX' TO 'L:\DATA\CAERPT1D\dba_db_NEW\dba_db_FG_IX.ndf' , 
	MOVE 'dba_db_FG_PK_DEF' TO 'L:\DATA\CAERPT1D\dba_db_NEW\dba_db_FG_PK_DEF.ndf' ,
	MOVE 'dba_db_FG_PK1_worlf' TO 'L:\DATA\CAERPT1D\dba_db_NEW\dba_db_FG_PK1_worlf.ndf'

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
9,867 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Olaf Helper 29,196 Reputation points
    2023-05-22T05:34:19.09+00:00

    I am working on dynamically restore DB.

    That's already not the best idea and if you want to use dynamic SQL then start learning about it https://www.sommarskog.se/dynamic_sql.html

    SET @SQL = @backup_files + CHAR(10) + 'WITH

    That code is more then wrong. If the dynamic SQL should contain hyphens ('), then you have to quote them.

    ... and much more issues with your code, e.g. missing spaces.

    Use PRINT command to get the content of the variable @ SQL to validate it.

    https://learn.microsoft.com/en-us/sql/t-sql/language-elements/print-transact-sql?view=sql-server-ver16

    0 comments No comments

  2. PercyTang-MSFT 5,706 Reputation points Microsoft Vendor
    2023-05-22T09:39:14.69+00:00

    Hi @Vijay Kumar

    Like Olaf said, your code confuses us.

    Dynamic SQL is a difficult syntax. You can refer to this document to improve your code.

    https://www.sqlshack.com/learn-sql-dynamic-sql/

    Best regards,

    Percy Tang

    0 comments No comments