Stored Procedure consist Add column, Update data for that column, and Select all data from that table

早过忘川 提交于 2019-12-08 03:08:03

问题


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!


回答1:


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




回答2:


I ran into this same issue and found that in addition to using dynamic sql I could solve it by cross joining to a temp table that had only one row. That caused the script compiler to not try to resolve the renamed column at compile time. Below is an example of what I did to solve the issue without using dynamic SQL

select '1' as SomeText into #dummytable

update q set q.ValueTXT = convert(varchar(255), q.ValueTXTTMP) from [dbo].[SomeImportantTable] q cross join #dummytable p


来源:https://stackoverflow.com/questions/1871246/stored-procedure-consist-add-column-update-data-for-that-column-and-select-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!