Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding a column in stored procedure

Can I have one single stored procedure to add a new column to a table and work on the column afterwords? For example, I have following stored procedure:

...

alter table tb1
add col1 varchar(1) null

insert into tb1(col1)
values ('Y')

I got an error saying

col1 is invalid.

like image 639
GLP Avatar asked Sep 10 '12 19:09

GLP


People also ask

How do I add a column in SP?

To add a column, click Add, click the field or repeating group for which you want to create a column, and then type a name for the column in the Column name box.

How add a column in SQL query?

We can use the ALTER TABLE statement to alter our existing table and add in this new column. The basic syntax for adding a new column is as follows: ALTER TABLE table_name ADD column_name data_type constraints; The SQL ALTER TABLE add column statement we have written above takes four arguments.

How do you add a column?

To insert a single column: Right-click the whole column to the right of where you want to add the new column, and then select Insert Columns. To insert multiple columns: Select the same number of columns to the right of where you want to add new ones. Right-click the selection, and then select Insert Columns.

How do you add a column in an update statement?

If we want to add multiple columns to the existing table using any single statement, we can use the below syntax: ALTER TABLE table_name (Name of the table) ADD [COLUMN] column_definition, (for adding column)


1 Answers

Try creating the table with a default value of 'Y' instead of inserting the values afterwards.

alter table tb1 add col1 varchar(1) not null DEFAULT ('Y')

You would need GO in between the two lines to have the table created, as per the GO documentation:

SQL Server utilities interpret GO as a signal that they should send the current batch of Transact-SQL statements to an instance of SQL Server.

However, you can't have GO statements in stored procedures.

EDIT

Alternately, you could use the EXEC statement to execute your code:

EXEC ('alter table tb1 add col1 varchar(1) null')
EXEC ('update tb1 set col1 = ''Y''')
like image 100
LittleBobbyTables - Au Revoir Avatar answered Oct 01 '22 16:10

LittleBobbyTables - Au Revoir