尝试使变量数据库名称的拖放操作动态化

时间:2019-03-25 20:45:19

标签: sql-server tsql

您知道如何在SQL Server中右键单击表并选择生成drop and create sql和生成restore sql吗?这就是我在下面列出的内容。第一个列表经过硬编码,可以与一个数据库一起使用。第二个清单是我的尝试,但没有成功。它的第一个+符号附近有语法错误。

工程

EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'pubs'
GO
use [pubs]

GO
use [master]

GO
USE [master]
GO
ALTER DATABASE [pubs] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
/****** Object:  Database [pubs]    Script Date: 3/25/2019 2:58:04 PM ******/
DROP DATABASE [pubs]
GO
RESTORE DATABASE [pubs] FROM  DISK = N'C:\Users\RSantia\pubs.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 5
GO

我的尝试

DECLARE @lib nvarchar(500) = 'pubs'

EXECUTE sp_executesql

N'EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = ' + '''' + @lib + '''' +
'GO
use ' + @lib + 
'GO
use [master]
GO
USE [master]
GO
ALTER DATABASE ' + @lib + ' SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
/****** Object:  Database [rstestdb100]    Script Date: 3/25/2019 2:58:04 PM ******/
DROP DATABASE ' + @lib + 
'GO
RESTORE DATABASE ' + @lib + ' FROM  DISK = C:\Users\RSantia\' + @lib + '.bak WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 5
GO'

1 个答案:

答案 0 :(得分:2)

当我执行较大的动态SQL语句时,我将生成的语句存储在NVARCHAR(MAX)变量中,然后在尝试执行它之前先打印它。然后,您可以解析生成的语句以查找语法错误,这将导致您进入动态SQL崩溃的地方。像这样:

DECLARE @lib nvarchar(500) = 'pubs'

DECLARE @SQL NVARCHAR(MAX) = 

N'EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = ' + '''' + @lib + '''' +
'GO
use ' + @lib + 
'GO
use [master]
GO
USE [master]
GO
ALTER DATABASE ' + @lib + ' SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
/****** Object:  Database [rstestdb100]    Script Date: 3/25/2019 2:58:04 PM ******/
DROP DATABASE ' + @lib + 
'GO
RESTORE DATABASE ' + @lib + ' FROM  DISK = C:\Users\RSantia\' + @lib + '.bak WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 5
GO'

PRINT @SQL

您生成的SQL语句如下:

EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = 'pubs'GO
use pubsGO
use [master]
GO
USE [master]
GO
ALTER DATABASE pubs SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
/****** Object:  Database [rstestdb100]    Script Date: 3/25/2019 2:58:04 PM ******/
DROP DATABASE pubsGO
RESTORE DATABASE pubs FROM  DISK = C:\Users\RSantia\pubs.bak WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 5
GO

您可以轻松地在那里看到您生成的语句有一些错误。请记住,仅因为脚本具有回车符并不意味着生成的SQL也将具有回车符。

我认为这可能是您想要的:

DECLARE @lib nvarchar(500) = 'pubs'

DECLARE @SQL NVARCHAR(MAX) = 

N'EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = ' + '''' + @lib + '''
GO
use ' + @lib + '
GO
use [master]
GO
USE [master]
GO
ALTER DATABASE ' + @lib + ' SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
/****** Object:  Database [rstestdb100]    Script Date: 3/25/2019 2:58:04 PM ******/
DROP DATABASE ' + @lib + 
'GO
RESTORE DATABASE ' + @lib + ' FROM  DISK = C:\Users\RSantia\' + @lib + '.bak WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 5
GO'

EXEC sys.sp_executesql @SQL