简体   繁体   中英

ALTER TABLE…ADD not working in SSMS

I'm trying to alter a table by adding a new column inside a stored procedure. Here's what I have:

USE [Lab5]
go
create procedure do_ver2 as
    alter table VehicleContract
        add trailerNr varchar(7) null;
    alter table VehicleContract
        add constraint FK_VehicleContract_Trailers foreign key (trailerNr) references Trailers(trailerNr);
go

The problem is... although it doesn't show any errors, it also doesn't create a new column either. Any idea why? It's T-SQL.

You need to use Dynamic-SQL to execute DDL statement inside stored procedure:

CREATE PROCEDURE do_ver2 AS
BEGIN
    EXEC('alter table VehicleContract add trailerNr varchar(7) null;');
    EXEC('alter table VehicleContract add constraint FK_VehicleContract_Trailers foreign key (trailerNr) references Trailers(trailerNr);');
END
GO

EDIT:

In your code without BEGIN and END your stored procedure contain only first statement. You should always add begin/end block.

USE [Lab5]
go
create procedure do_ver2 as
    EXEC('alter table VehicleContract
        add trailerNr varchar(7) null;');
    EXEC('alter table VehicleContract
        add constraint FK_VehicleContract_Trailers 
        foreign key (trailerNr) references Trailers(trailerNr);');
go

If you check the the code of stored procedure you will see that it have only:

 create procedure do_ver2 as
        EXEC('alter table VehicleContract add trailerNr varchar(7) null;');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM