0

Here is the base table layout:

create table employees (employeeid int not null IDENTITY, 
firstname varchar(50), middlename varchar(50), lastname varchar(50), 
assumedfirstname default(firstname), assumedname as concat(assumedfirstname,' ',lastname)

I understand that the assumedfirstname column is not being created correctly in the above statement; that default values must be scalar expressions and cannot be column names. That said, the above statement clearly illustrates my intent. That is, I wish for the assumedfirstname column to automatically be populated with the value found in firstname but allow explicit replacement with a separate string later. In this way, assumedname will always represent either a default of the person's first and last names or an explicitly entered assumedfirstname and their last name.

As such, a computed column will not work in this situation.

4

1 回答 1

2

不能设置为默认,但可以用触发器模拟;

CREATE TABLE employees (
  employeeid INT NOT NULL IDENTITY, 
  firstname VARCHAR(50), 
  middlename VARCHAR(50), 
  lastname VARCHAR(50), 
  assumedfirstname VARCHAR(50), 
  assumedname AS assumedfirstname + ' ' + lastname
);

CREATE TRIGGER MyTrigger on employees
FOR UPDATE, INSERT AS  
UPDATE e 
  SET e.assumedfirstname = COALESCE(e.assumedfirstname, i.firstname)
FROM employees e
JOIN inserted i
  ON i.employeeid=e.employeeid;

如果设置为 null(即未设置),此触发器会将假定的名字更新为名字的值。

一个用于测试的 SQLfiddle

于 2013-05-22T18:55:22.783 回答