我几乎已经用Sql Server替换了我们的应用程序后端,但我遇到了一个问题。以下Access查询不适用于Sql Server。
SELECT table1.*
FROM table1
INNER JOIN (table2
INNER JOIN table3
ON ( table2.custkey = table3.custkey )
AND ( table2.sequence = table3.sequence ))
ON table1.account = table2.account
WHERE (( LEFT(table2.keyid, 1) = 'B' ))
ORDER BY table3.lastname & table3.firstname,
table1.account;
我已经尝试过此声明的多种变体,但无法使其发挥作用。对此声明的一些帮助将帮助我修改其他一些。任何帮助将不胜感激。
答案 0 :(得分:2)
唯一突出的是“&
”,它在SQL Server中是+
。但是,访问中的&
也将NULL值视为空字符串,需要在SQL Server中使用ISNULL
进一步处理:
SELECT table1.*
FROM table1
INNER JOIN (table2
INNER JOIN table3
ON ( table2.custkey = table3.custkey )
AND ( table2.sequence = table3.sequence ))
ON table1.account = table2.account
WHERE (( LEFT(table2.keyid, 1) = 'B' ))
ORDER BY isnull(table3.lastname,'') + isnull(table3.firstname,''),
table1.account;
如果我是从头开始在SQL Server中编写查询,我可能会连续进行连接,而不是在加入t1之前在括号中执行t2-t3。第一个字符的测试也将表示为LIKE(个人偏好)。
SELECT table1.*
FROM table1
JOIN table2 ON table1.account = table2.account
JOIN table3 ON table2.custkey = table3.custkey AND table2.sequence = table3.sequence
WHERE table2.keyid LIKE 'B%'
ORDER BY isnull(table3.lastname,'') + isnull(table3.firstname,''), table1.account;
答案 1 :(得分:1)
SELECT table1.*
FROM table1
INNER JOIN table2 ON table1.account = table2.account
INNER JOIN table3 ON ( table2.custkey = table3.custkey )
AND ( table2.sequence = table3.sequence )
WHERE LEFT(table2.keyid, 1) = 'B'
ORDER BY table3.lastname, table3.firstname, table1.account;
如果您希望where子句适合索引,请使用LIKE重写:
SELECT table1.*
FROM table1
INNER JOIN table2 ON table1.account = table2.account
INNER JOIN table3 ON ( table2.custkey = table3.custkey )
AND ( table2.sequence = table3.sequence )
WHERE table2.keyid LIKE 'B%'
ORDER BY table3.lastname, table3.firstname, table1.account;