2012-04-12 79 views
0

我有销售代表,它们通过客户的邮政编码的前三位数字与客户相关联 - 这仅适用于美国客户。 Profile_Zip表有两列,分别代表代表邮政编码前三位数字的代表和三位数字。在保存客户记录配置表使用子串识别记录并更新记录

Profile_Key  Three_Digits 
123456   610 
123456   611 
123456   612 

两个字段邮编(邮政编码),并保持销售代表的Profile_Key的关联字段。

我需要运行一个查询,使用Profile_Zip表中rep的配置文件键更新Customer的association_key。这是我一直在努力的。

update profile set association_key = 
(select profile_key from profile_zip where three_digits = 
(Select substring(zip, 1, 3) as ZipPrefix 
From profile group by profile.zip)) 

我知道为什么我得到这个错误,我无法弄清楚如何使查询工作,或者如果子字符串是正确的/最佳途径可走。

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询被用作表达式时,这是不允许的。

是否有另一种方法可以做到这一点? 谢谢。

配置文件表。 John Doe是rep(profile_type = 4),Mary是顾客(profile_type = 6)。 John的profile_key位于Mary的Association_key字段中,这就是绑定它们的地方。当然也有在记录(地址,电话等)更多的领域

Profile_key Profile_Type_Key First_Name Last_Name Zip Association_Key ... 
    123456    4   John   Doe  92112  
    987654    6   Mary   Smith 90210  123456 

回答

1

我认为这确实你想在那里做什么:

UPDATE P 
SET Association_Key = PZ.Profile_Key 
FROM [Profile] P 
INNER JOIN Profile_Zip PZ 
    ON PZ.Three_Digits = SUBSTRING(P.Zip, 1, 3) 

的问题是,你要设定一个标量值结果集。在这种情况下,您需要更新结果集,然后使用正确的标量值。

+0

感谢您的帮助。这个伎俩。 – Stan 2012-04-12 21:15:49

0

错误

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

表明您使用的是=当你需要使用IN。当使用=时,系统仅预期1个结果。

特别,我猜:

Select substring(zip, 1, 3) as ZipPrefix 
From profile 
group by profile.zip 

返回大量的子字符串。在子查询之外使用IN

+0

不,你错了。不是那种情况。请作者发布所有相关表格的结构以及您为Profile_Zip所做的工作 – heximal 2012-04-12 19:45:43

+0

您是否可以分享关于您的表格结构和数据的其他信息? – 2012-04-12 19:46:41

+0

我已经为剖析表添加了表结构。谢谢。 – Stan 2012-04-12 20:25:28