SQL Server 2012执行代码报错#TEST已存在,未打印Begin求解原因
Let's break down the two key issues you're facing: the "object named '#TEST' already exists" error, and why PRINT 'Begin' never runs.
1. Why PRINT 'Begin' Doesn't Execute
SQL Server processes code batches in two phases: compilation first, then execution. If the compiler detects a problem (like trying to create a temporary table that already exists in your current session), it aborts the entire batch before any code runs. That means your PRINT 'Begin' statement never gets to execute—compilation fails so early, nothing in the batch is run.
2. Why the "#TEST already exists" Error Happens
Local temporary tables (named with a single #) are tied to your current SQL Server session. If you ran a script that created #TEST earlier in the same SSMS session (even if you closed the query window but didn't disconnect from the server), the table still lives in the tempdb database until you either:
- Explicitly drop it with
DROP TABLE #TEST; - Close the entire SSMS session (which ends the connection and automatically cleans up temporary objects)
Since the table is still present when you run your new script, the compiler throws the duplicate object error immediately.
Fixes for Your Script
To get your script working as expected, add a check to drop the temporary table if it exists before trying to create it. For SQL Server 2012 (which doesn't support the newer DROP TABLE IF EXISTS syntax), use this pattern:
-- Clean up existing #TEST if it exists IF OBJECT_ID('tempdb..#TEST') IS NOT NULL DROP TABLE #TEST; PRINT 'Begin'; -- Create and populate the temporary table CREATE TABLE #TEST (A VARCHAR(10)); INSERT INTO #TEST VALUES ('1'); -- Verify the result SELECT * FROM #TEST;
This ensures any leftover #TEST table is removed before your script proceeds, allowing the batch to compile successfully and run all your code (including the PRINT statement).
If you're running multiple batches (separated by GO), make sure each batch that uses #TEST handles cleanup appropriately, or avoid reusing the same temporary table name across batches unless you intend to retain the existing data.
内容的提问来源于stack exchange,提问作者Simone

