If you want to do this directly in the table then you can create a persisted computed column
that will do this for you. You'll have to make a function to do the calculation you're after (either a CASE
or IF EXISTS
).
The advantage of a computed column is that it will keep itself up to date, you don't have to run a regular update to make sure that it's in there.
Function;
CREATE FUNCTION dbo.TownCheck (@Town VARCHAR(1))
RETURNS VARCHAR(1)
AS BEGIN
DECLARE @TownExists VARCHAR(1)
SELECT @TownExists = MAX('X') FROM dbo.TownNames WHERE TownName = @Town
RETURN @TownExists
END
Let's make your sample data;
CREATE TABLE DataTable (Fname varchar(5), Surname varchar(6), Town varchar(10), Postcode varchar(8), Flag varchar(1))
INSERT INTO DataTable (Fname, Surname, Town, Postcode)
VALUES
('Alan','Jones','Colchester','CO1 2RT')
,('Steve','Smith','Lincoln','LN23 7TY')
,('Jeff','Lilly','Swindon','SN1 6LK')
,('Sarah','Thomas','Lincoln','LN56 9TT')
And the second table;
CREATE TABLE TownNames (TownName varchar(10))
INSERT INTO TownNames
VALUES
('Lincoln')
,('Swindon')
You can't alter a column to make it calculated so you have to drop it and then recreate it (I've assumed you already have this table, if you don't then do this at the point of creation of the table);
ALTER TABLE dbo.DataTable
DROP COLUMN Flag
ALTER TABLE dbo.DataTable
ADD Flag AS dbo.TownCheck(Town)
Now your DataTable will look like this;
Fname Surname Town Postcode Flag
Alan Jones Colchester CO1 2RT NULL
Steve Smith Lincoln LN23 7TY X
Jeff Lilly Swindon SN1 6LK X
Sarah Thomas Lincoln LN56 9TT X
Edit:
This will work if the TownNames table is updated. If you insert the missing town;
INSERT INTO TownNames
VALUES ('Colchester')
You get this result;
Fname Surname Town Postcode Flag
Alan Jones Colchester CO1 2RT X
Steve Smith Lincoln LN23 7TY X
Jeff Lilly Swindon SN1 6LK X
Sarah Thomas Lincoln LN56 9TT X
Further reading;
define a computed column reference another table