求助:使用Visual Studio生成的SQL脚本在MSSQL创建数据库失败
Hey there, let's get your database back up and running! The root cause of your failure is super straightforward: your generated EDMX script tries to USE [CustomersDB] right off the bat, but that database doesn't exist anymore (since you lost the .mdf file). Here's how to fix this step by step:
Step 1: Modify the Generated SQL Script
First, we need to add a database creation block at the very top of your existing script. This ensures the database exists before we try to use it. Here's what to prepend:
-- Create CustomersDB if it doesn't already exist IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = N'CustomersDB') BEGIN CREATE DATABASE [CustomersDB]; END GO
Then paste your original EDMX-generated script right after this block (starting with SET QUOTED_IDENTIFIER OFF; GO USE [CustomersDB]; ...).
Step 2: Execute the Script Correctly
A quick heads-up: you mentioned using Ctrl+F5 to execute — that's actually just for syntax checking, not running the script! Follow these steps instead:
- Open SQL Server Management Studio (SSMS)
- Connect to your SQL Server instance
- Make sure your query window is connected to the
masterdatabase (this is crucial, since we can't create a new database from inside a non-system database) - Paste the modified script into the query window
- Press
F5(or click the "Execute" button) to run the full script
Bonus Troubleshooting Tips
- If you get permission errors, make sure your SQL Server account has the
dbcreatororsysadminserver role (you need these to create new databases) - If your original database had custom logins, users, or stored procedures not included in the EDMX model, you'll need to recreate those separately
- Double-check the rest of your script for any references to missing objects (like custom file paths for .mdf/.ldf files) — the
CREATE DATABASEcommand above uses default server paths, but you can addON PRIMARYclauses if you need to specify custom storage locations
内容的提问来源于stack exchange,提问作者amir

