【发布时间】:2011-01-05 21:55:27
【问题描述】:
我不确定我想要做什么的语法。我需要根据条件选择几个地址字段。
逻辑是可靠的,但似乎语法不正确。它在关键字“Case”、“Else”、“Else”附近出现“语法不正确”的错误。 思路是如果isprimary=1则将地址插入表中,如果没有primary则插入isactive=1的最新地址,如果没有active则插入最新地址。
请帮忙
-- 为记录 02 选择一个最佳地址
DECLARE @ygcaddress TABLE
(
[AccountID] varchar(10),
[Address1] varchar(25),
[City] varchar(22),
[State] varchar(3),
[Zip] varchar(9)
)
INSERT INTO @ygcaddress
CASE
WHEN Address.IsPrimary=1
THEN
SELECT
LEFT(Address.AddressLine1,25),
Address.City,
[Lookup].LookupValue,
Address.Zip
FROM (((AccountPerson INNER JOIN Account ON AccountPerson.AccountID=Account.AccountID)
INNER JOIN Address ON AccountPerson.PersonID=Address.PersonID)
INNER JOIN @ygcaddress y ON Account.AccountID=y.AccountID)
INNER JOIN [Lookup] ON Address.StateID=[Lookup].LookupID
WHERE Address.IsPrimary=1
ELSE
CASE
WHEN Address.IsActive=1
THEN
SELECT TOP 1
LEFT(Address.AddressLine1,25),
Address.City,
[Lookup].LookupValue,
Address.Zip
FROM (((AccountPerson INNER JOIN Account ON AccountPerson.AccountID=Account.AccountID)
INNER JOIN Address ON AccountPerson.PersonID=Address.PersonID)
INNER JOIN @ygcaddress y ON Account.AccountID=y.AccountID)
INNER JOIN [Lookup] ON Address.StateID=[Lookup].LookupID
WHERE Address.IsActive=1
ELSE
SELECT TOP 1
LEFT(Address.AddressLine1,25),
Address.City,
[Lookup].LookupValue,
Address.Zip
FROM (((AccountPerson INNER JOIN Account ON AccountPerson.AccountID=Account.AccountID)
INNER JOIN Address ON AccountPerson.PersonID=Address.PersonID)
INNER JOIN @ygcaddress y ON Account.AccountID=y.AccountID)
INNER JOIN [Lookup] ON Address.StateID=[Lookup].LookupID
END
END
【问题讨论】:
-
能否在不丢失问题本质的情况下简化查询?
标签: sql sql-server-2005 select case