0

My question is in my title, I have defined a stored procedure with the following

CREATE PROCEDURE [dbo].[sp_doStuff]   
       @path CHAR(256), @databaseName sysname, @backupType CHAR(1)  
AS  
BEGIN 
   SET NOCOUNT ON;  

   DECLARE @sqlCommand NVARCHAR(1000)  
   DECLARE @dateTime NVARCHAR(20)  

   SELECT @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),111),'/','') +  
   REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')   

   IF @backupType = 'F'  
           SET @sqlCommand = 'BACKUP DATABASE ' + @databaseName +  
           ' TO DISK = ' + @path + @databaseName + '_Full_' + @dateTime + '.BAK'''  

   IF @backupType = 'D'  
           SET @sqlCommand = 'BACKUP DATABASE ' + @databaseName +  
           ' TO DISK = ' + @path + @databaseName + '_Diff_' + @dateTime + '.BAK'' WITH DIFFERENTIAL' 

   IF @backupType = 'L'  
           SET @sqlCommand = 'BACKUP LOG ' + @databaseName +  
           ' TO DISK = ' + @path + @databaseName + '_Log_' + @dateTime + '.TRN'''  

   EXECUTE sp_executesql @sqlCommand  
END

When I want to run the following command:

[dbo].[sp_doStuff] 'D:\FolderName\', 'MyDatabase', 'F';

It gives me this error:

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'D:'.
Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark after the character string ''.

Does anyone have a clue why this gives errors? I can make it work by hard coding the path into the procedure, but I want to be able to pass it in a a parameter.

1

2 Answers 2

3

Try

' TO DISK = ''' + @path + @databaseName

etc...

0
1

It is not the issue of parameter. you are making wrong execute statement that uses single quote and you have not escaped that one..

you can escape single quote using two single quotes (NOT double quote). If a character string enclosed in single quotation marks contains an embedded quotation mark, represent the embedded single quotation mark with two single quotation marks.

e.g.

USE AdventureWorks
GO
SELECT *
FROM Person.Address
WHERE City = 'Villeneuve-d''Ascq'
GO

Ref:
Escape Character in SQL
SQL SERVER – How to Escape Single Quotes – Fix: Error: 105 Unclosed quotation mark after the character string ‘

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.