Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Server 2008 sp_executesql syntax help - I think my quotes are not correct

Using SQL Server 2008 I'm trying to build up a string and execute it with sp_executesql. I obviously have some quotes wrong. It appears to run, but the database is not dropped. Can someone help me to correct the syntax?

USE [master]
GO

DECLARE @sql NVARCHAR(500)
SET @sql = N' IF EXISTS (SELECT NAME FROM master.sys.databases sd where name =''@DBName'') 
BEGIN
  ALTER DATABASE [@DBName] SET  RESTRICTED_USER WITH ROLLBACK IMMEDIATE
  ALTER DATABASE [@DBName] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
  DROP DATABASE [@DBName]
END';

EXECUTE sp_executesql @sql, N'@DBName sysname', @DBName = 'ReapirInformation'

GO

I've tried adding and removing quotation marks but I can't seem to dial in the correct mix. Any tips or tricks are certainly welcome.

Thanks,
~ck in San Diego

like image 756
Hcabnettek Avatar asked Jan 01 '26 12:01

Hcabnettek


1 Answers

Dynamic SQL does not work like that.
You still cannot pass parameters to a dynamic string that will be used in place of object names.

You have to construct the query string yourself, manually replacing @DBName with actual value. However, you can use a parameter on the right side of a equation, without any quotes.

Also, when putting an object name into a query, always use the QUOTENAME function. It will correctly escape the name so there's no sql injection or unwanted behaviour caused by certain characters in an object's name.

SET @sql = N' IF EXISTS (SELECT NAME FROM master.sys.databases sd where name = @DBName)
BEGIN
  ALTER DATABASE ' + quotename(@DBName, '[') + N' SET  RESTRICTED_USER WITH ROLLBACK IMMEDIATE
  ALTER DATABASE ' + quotename(@DBName, '[') + N' SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
  DROP DATABASE ' + quotename(@DBName, '[') + N' 
END';
like image 122
GSerg Avatar answered Jan 03 '26 08:01

GSerg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!