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

梦想的初衷 提交于 2019-12-06 09:19:08

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

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