SQL Server Setting one of the columns in default value

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

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:

  1. ID Name Address Remarks
  2. 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:

  1. CREATE TABLE YourTable (
  2. ID INT,
  3. Name NVARCHAR(50),
  4. Address NVARCHAR(50),
  5. Remarks AS ('Name: ' + Name + ', Address: ' + Address)
  6. )
  7. INSERT INTO YourTable (ID, Name, Address)
  8. VALUES (1, 'Richard', 'USA'), (2, 'Amit', 'India');

Trigger Method:

  1. CREATE TABLE YourTable (
  2. ID INT,
  3. Name NVARCHAR(50),
  4. Address NVARCHAR(50),
  5. Remarks NVARCHAR(MAX)
  6. )
  7. CREATE TRIGGER SetRemarks ON YourTable
  8. AFTER INSERT
  9. AS
  10. BEGIN
  11. UPDATE YourTable
  12. SET Remarks = 'Name: ' + INSERTED.Name + ', Address: ' + INSERTED.Address
  13. FROM YourTable
  14. INNER JOIN INSERTED ON YourTable.ID = INSERTED.ID
  15. END
  16. INSERT INTO YourTable (ID, Name, Address)
  17. VALUES (1, 'Richard', 'USA'), (2, 'Amit', 'India');
展开查看全部

相关问题