views:

242

answers:

2

I've written a stored procedure as following:

  CREATE PROC spSoNguoiThan 
   @SNT int
    AS 
       begin 
    IF not exists (select column_name from  INFORMATION_SCHEMA.columns where
                    table_name = 'NhanVien' and   column_name = 'SoNguoiThan')  

         ALTER TABLE NhanVien ADD   SoNguoiThan int
    else 
           begin
     UPDATE  NhanVien
                SET  NhanVien.SoNguoiThan = (SELECT  Count(MaNguoiThan)FROM NguoiThan
                                             WHERE MaNV=NhanVien.MaNV 
                                             GROUP BY  NhanVien.MaNV)   
           end   

    SELECT *
        FROM NhanVien 
    WHERE    SoNguoiThan>@SNT
 end 
GO

Then I get the error :

Server: Msg 207, Level 16, State 1, Procedure spSoNguoiThan, Line 12
Invalid column name 'SoNguoiThan'.
Server: Msg 207, Level 16, State 1, Procedure spSoNguoiThan, Line 15
Invalid column name 'SoNguoiThan'.

Who can help me?

Thanks!

A: 

When I run

IF not exists (select column_name from  INFORMATION_SCHEMA.columns where
                table_name = 'NhanVien' and   column_name = 'SoNguoiThan')  
            ALTER TABLE NhanVien ADD   SoNguoiThan int

and then I run Update Statement and Select :

UPDATE  NhanVien
            SET  NhanVien.SoNguoiThan = (SELECT  Count(MaNguoiThan)FROM NguoiThan
                                         WHERE MaNV=NhanVien.MaNV 
                                         GROUP BY  NhanVien.MaNV)   

SELECT *
    FROM NhanVien 
WHERE    SoNguoiThan>@SNT

then no error.

Can you help me?

yes - if you run this as two separate statements in SQL Server Mgmt Studio, it will work - the first one just adds the new column, and when the second one gets parsed, the column exists, so it works.This is **NOT** true if you do this inside a single statement in your stored proc! As gbn already said: the stored proc's code will be parsed in its entirety and the problem is that the column DOES NOT EXIST YET when the code gets parsed! You **cannot** add a new column to a table and use that new coulmn inside the same stored proc script - you need to change your approach.
marc_s
Can you help me edit my problem follow you?Thanks!
+4  A: 

When the stored proc is parsed during CREATE the column does not exist so you get an error.

Running the internal code line by line works because they are separate. The 2nd batch (UPDATE) runs because the column exists.

The only way around this would be to use dynamic SQL for the update and select so it's not parsed until EXECUTE time (not CREATE time like now).

However, this is something I really would not do: DDL and DML in the same bit of code

gbn
definitely - do **not** ever mix DDL and DML in a single proc - bad bad bad design
marc_s
@marc_s: I'd make an exception for TRUNCATE TABLE, rarely, and temp tables. Though temp tables seem to be less nescessary with each release of SQL Server.
Shannon Severance