此脚本无法从PowerShell(sqlcmd)直接从SQL Management Studio执行:
IF db_id('BANANATEST') is not null
BEGIN
print 'DB BANANATEST already exists. NO ACTION TAKEN.'
END
ELSE
BEGIN
print 'DB BANANATEST does NOT exist.'
print 'Restoring a backup of BANANATEST'
RESTORE DATABASE BANANATEST
FROM DISK = 'BANANATEST.original.bak' ;
print 'Creating User BANANATEST'
USE master
If Exists (select loginname from master.dbo.syslogins where name ='BANANATEST')
Begin
DROP LOGIN [BANANATEST]
END
CREATE LOGIN [BANANATEST] WITH PASSWORD=N'BANANATEST', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
USE BANANATEST
ALTER USER [BANANATEST] WITH LOGIN = [BANANATEST]
END
错误是语法。
Msg 911,Level 16,State 1,Line 20数据库'BANANATEST'没有 存在。确保正确输入名称。
虽然准确,但在查询“编译”时不存在BANANATEST DB ... SQL Server没有意识到数据库 WILL 在到达此行时存在。
如何让它工作?要么忽略语法检查,要么忽略它的工作......
注意:备份附带一个BANANATEST usr,我想介绍两种情况:
答案 0 :(得分:1)
你可以使用#temp tables
来解决这个问题CREATE table #temp12 (restore1 bit)
IF db_id('BANANATEST') is not null
BEGIN
print 'DB BANANATEST already exists. NO ACTION TAKEN.'
END
ELSE
BEGIN
print 'DB BANANATEST does NOT exist.'
print 'Restoring a backup of BANANATEST'
RESTORE DATABASE BANANATEST
FROM DISK = 'BANANATEST.original.bak' ;
INSERT INTO #temp12 VALUES ('1')
print 'Creating User BANANATEST'
END
GO
USE master
IF EXISTS (SELECT 1 from #TEMP12)
BEGIN
If Exists (select loginname from master.dbo.syslogins where name ='BANANATEST')
Begin
DROP LOGIN [BANANATEST]
END
CREATE LOGIN [BANANATEST] WITH PASSWORD=N'BANANATEST', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
USE BANANATEST
ALTER USER [BANANATEST] WITH LOGIN = [BANANATEST]
END
DROP TABLE #temp12