문제

CREATE PROCEDURE  _InsertAttbts
    @Attribute VARCHAR(100)

AS 

    IF  NOT EXISTS (SELECT * FROM dbo.Attributes WHERE Attribute = @Attribute)

    INSERT INTO dbo.Attributes(Attribute)
                VALUES(@Attribute)

    IF  NOT EXISTS (SELECT * FROM DBO.Products WHERE Pname =@Attribute)

        ALTER TABLE PRODUCTS
        ADD @Attribute varchar(100)

Here Products is my master table and Attributes is its child table. My task is if the user tries to insert a new row it checks whether the row is existing, if not it wants to add new row in the product table and same time it should be inserted the same value in the attribute field in the attributes table...

I am using SP in SQL Server 2012.

Plz Help!

Thanks....

도움이 되었습니까?

해결책

You need to do this with dynamic SQL, I think.

CREATE PROCEDURE _InsertAttbts @Attribute VARCHAR(100)
AS
BEGIN
    IF NOT EXISTS (SELECT * FROM dbo.Attributes WHERE Attribute = @Attribute)
    BEGIN
        INSERT INTO dbo.Attributes(Attribute)
            VALUES(@Attribute);

        declare @sql nvarchar(max) = 'ALTER TABLE PRODUCTS ADD '+@Attribute+' varchar(100)';
        exec sp_executesql @sql;
    END;
END;

I have no idea why you want to do this. You can get the list of columns using INFORMATION_SCHEMA.COLUMNS or one of the system tables.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top