I use dynamic sql to create database an tables
this is sql script
DECLARE @DatabaseName VARCHAR(50) = N'test';
EXECUTE ('CREATE DATABASE [' +@DatabaseName+']');
EXECUTE('USE ' + @DatabaseName)
GO
CREATE SCHEMA [Framework]
GO
the error I get
Msg 2714, Level 16, State 6, Line 1
There is already an object named 'Framework' in the database.
Msg 2759, Level 16, State 0, Line 1
CREATE SCHEMA failed due to previous errors
.
this error because EXECUTE('USE ' + @DatabaseName) not work
I try to use
SET @SQL02 = 'USE ['+ convert(nvarchar(50),@DatabaseName) +']; SELECT DB_NAME();'
exec sp_executesql @SQL02
but not work
what I can do?
DECLARE @Query VARCHAR(200);
SET @Query = CONCAT('USE ', QUOTENAME('<MyDatabase>'), '; ', 'select DB_NAME();');
EXECUTE (@Query);
This will return <MyDatabase>
as long as you remain within one EXECUTE
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With