all groups > sql server (alternate) > march 2004 >
You're in the

sql server (alternate)

group:

Best SQL possible



Best SQL possible bbigler NO[at]SPAM yahoo.com
3/19/2004 3:04:44 PM
sql server (alternate): By using Access as a front end to SQL server, I finally came up with a
statement that works (I think!?), but it doesn't seem elegant. Can
anyone help with a better one?

--Brent

======================================


Table1
AccountNumber
Shares
CUSIP

Table2
AccountNumber
Shares
SecurityID

Table3
SecurityID
CUSIP

I need to update the shares in Table2 (from Table1) where a) the
AccountNumber in Table2 matches Table1, and b) the CUSIP in Table1
matches the CUSIP in Table3.

Here's what I ended up with:

Update Table2 SET Table2.Shares = Table1.Shares FROM Table1 INNER JOIN
Table3 ON Table1.CUSIP = Table3.CUSIP INNER JOIN Table2 ON
Table3.SecurityID = Table2.SecurityID AND Table1.AccountNumber =
Table2.AccountNumber

The statement returns extra accounts sometimes -- maybe it's a bad
Re: Best SQL possible David Portas
3/20/2004 9:24:32 AM
Here's an alternative (standard and "safer") way to write your UPDATE
statement but without proper tables structures or sample data I have no way
of testing if this will do what you require. If this code gives you the
error "Subquery returned more than 1 value" then probably the statement you
posted won't work the way you expect either.

UPDATE Table2
SET shares =
(SELECT T1.shares
FROM Table1 AS T1
JOIN Table3 AS T3
ON T1.cusip = T3.cusip
AND T1.accountnumber = Table2.accountnumber
AND T3.securityid = Table2.securityid)

What does "returns extra accounts" mean? If you need more help, please post
DDL (CREATE TABLE statements including primary and foreign keys and
constraints) and post a few rows of sample data as INSERT statements.

--
David Portas
SQL Server MVP
--

Re: Best SQL possible John Bell
3/25/2004 11:22:53 PM
Hi

It is better to post the DDL (CREATE TABLE statements etc) rather than
pseudo-schemas along with example data (as insert statements). That way any
ambiguities are avoided. Without knowing the data it is hard to comment,
but I would try not to swap between CUSID and AccountNumber.

John


[quoted text, click to view]

AddThis Social Bookmark Button