我想在现有表中添加一列,为两个查询返回“不匹配”:
select * from dbo.customer
where cus_title IN ('MRS','DAME','SISTER','MISS','MADAME','LADY','MS')
and cus_gender <> 'F'
select * from pv_customer
where cus_title IN ('FATHER','SIR','MR')
and cus_gender <> 'M'
或'匹配',如果未从上述两个查询中选择?
是否有人能够协助进行alter table查询?
非常感谢
答案 0 :(得分:1)
您只需添加列并运行如下更新语句:
ALTER TABLE <table_name>
ADD COLUMN match_status VARCHAR(10) NULL;
UPDATE <table_name> SET match_status = 'match';
假设您正在更新的这个表有一个客户ID的外键,那么您将使用以下内容更新非匹配:
UPDATE <table_name> SET match_status = 'non-match'
WHERE customerId IN (select customerId from dbo.customer where cus_title IN ('MRS','DAME','SISTER','MISS','MADAME','LADY','MS') and cus_gender <> 'F')
OR customerId IN (select customerId from pv_customer where cus_title IN ('FATHER','SIR','MR') and cus_gender <> 'M');
答案 1 :(得分:1)
这听起来像计算列的工作!与运行UPDATE
不同,计算列的优点是,如果添加新行或更新现有行,则会自动更新。
创建一个这样的函数:
CREATE FUNCTION [dbo].[fn_GenderMatch](@title VARCHAR(50), @gender CHAR(1)) RETURNS VARCHAR(10)
WITH SCHEMABINDING AS
BEGIN
IF (((@title IN ('MRS', 'MS', 'MISS')) AND (@gender = 'M'))
OR
((@title IN ('MR', 'SIR', 'FATHER')) AND (@gender = 'F')))
BEGIN
RETURN 'non-match'
END
RETURN 'match'
END
GO
如果要在此列上编制索引,WITH SCHEMABINDING
很重要!虽然,如果要索引,我建议更改函数以返回BIT
。哎呀,使用BIT
对于存储来说也更好,而且对于其他比较也更清洁。
然后像这样改变你的桌子:
ALTER TABLE [dbo].[customer] ADD [MisMatch] AS [dbo].[fn_GenderMatch]([cus_title],[cus_gender])
答案 2 :(得分:0)
ALTER TABLE [SomeTable] ADD COLUMN Check VARCHAR(10)
UPDATE [SomeTable]
SET Check = 'No Match'
UPDATE S
SET Check = 'Match'
FROM
[SomeTable] S JOIN dbo.Customers C ON s.CustomerID = C.CustomerId
AND C.cus_title IN
('MRS','DAME','SISTER','MISS','MADAME','LADY','MS') and C.cus_gender <>
'F'
JOIN Pv_Customer P ON S.CustomerID = P.CustomerID AND
P.cus_title IN ('FATHER','SIR','MR')
and P.cus_gender <> 'M'