Why does Microsoft SQL Server check columns but not tables in stored procs?

前端 未结 2 449
难免孤独
难免孤独 2020-12-25 14:42

Microsoft SQL Server seems to check column name validity, but not table name validity when defining stored procedures. If it detects that a referenced table name exists cur

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-25 15:25

    This is called deferred name resolution.

    There is no way of turning it off. You can use dynamic SQL or (a nasty hack!) add a reference to a non existent table so that compilation of that statement is deferred.

    CREATE PROCEDURE [dbo].[MyProcedure]
    AS
    BEGIN
    
    CREATE TABLE #Dummy (c int)
    
        SELECT
            NonExistantCol1, NonExistantCol2, NonExistantCol3
        FROM
            ExistantTable 
        WHERE NOT EXISTS(SELECT * FROM #Dummy)    
    
    
    DROP TABLE #Dummy
    
    END
    GO
    

提交回复
热议问题