SQL Server Setting one of the columns in default value

qcbq4gxm  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(72)

Is there anyway to set as default value one of the columns or more in SQL Server? I normally use as default value for date only ex: getdate() but I haven’t tried other columns.

Example:

ID Name    Address Remarks
1  Richard USA     Name: Richard,Address: USA

I want to concatenate Name and Address as default value or bindings of Remarks. Tried ‘Name: ’ + [Name] + ‘,‘ + ‘Address: ’+[Address] it doesn’t work.

gopyfrb3

gopyfrb31#

You can't directly set computed columns based on other column values within the DEFAULT constraint. You can achieve this using computed columns or triggers to generate a dynamic value based on other column values.

Computed Column Method:

CREATE TABLE YourTable (
    ID INT,
    Name NVARCHAR(50),
    Address NVARCHAR(50),
    Remarks AS ('Name: ' + Name + ', Address: ' + Address)
)

INSERT INTO YourTable (ID, Name, Address)
VALUES (1, 'Richard', 'USA'), (2, 'Amit', 'India');

Trigger Method:

CREATE TABLE YourTable (
    ID INT,
    Name NVARCHAR(50),
    Address NVARCHAR(50),
    Remarks NVARCHAR(MAX)
)

CREATE TRIGGER SetRemarks ON YourTable
AFTER INSERT
AS
BEGIN
    UPDATE YourTable
    SET Remarks = 'Name: ' + INSERTED.Name + ', Address: ' + INSERTED.Address
    FROM YourTable
    INNER JOIN INSERTED ON YourTable.ID = INSERTED.ID
END

INSERT INTO YourTable (ID, Name, Address)
VALUES (1, 'Richard', 'USA'), (2, 'Amit', 'India');

相关问题