How to pass a path to a stored procedure?

不想你离开。 提交于 2019-12-11 14:20:06

问题


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:


Try

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

etc...




回答2:


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 ‘



来源:https://stackoverflow.com/questions/10427451/how-to-pass-a-path-to-a-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!