我们所有使用关系数据库的人都知道(或正在学习)SQL是不同的。获得期望的结果,并有效地这样做,涉及到一个乏味的过程,其部分特征是学习不熟悉的范例,并发现一些我们最熟悉的编程模式在这里不起作用。常见的反模式是什么?


当前回答

临时表滥用。

特别是这类事情:

SELECT personid, firstname, lastname, age
INTO #tmpPeople
FROM People
WHERE lastname like 's%'

DELETE FROM #tmpPeople
WHERE firstname = 'John'

DELETE FROM #tmpPeople
WHERE firstname = 'Jon'

DELETE FROM #tmpPeople
WHERE age > 35

UPDATE People
SET firstname = 'Fred'
WHERE personid IN (SELECT personid from #tmpPeople)

不要从查询中构建临时表,只是为了删除不需要的行。

是的,我在生产db中看到过这种形式的代码页。

其他回答

同一查询中的相同子查询。

使用@@IDENTITY代替SCOPE_IDENTITY()

引自以下回答:

@@IDENTITY returns the last identity value generated for any table in the current session, across all scopes. You need to be careful here, since it's across scopes. You could get a value from a trigger, instead of your current statement. SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope. Generally what you want to use. IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope. This lets you specify which table you want the value from, in case the two above aren't quite what you need (very rare). You could use this if you want to get the current IDENTITY value for a table that you have not inserted a record into.

我最担心的是450列的访问表,这些表是由总经理最好的朋友狗美容师的8岁儿子整理的,还有那个不可靠的查找表,它之所以存在,是因为有人不知道如何正确地规范化数据结构。

通常,这个查找表是这样的:

ID INT,
Name NVARCHAR(132),
IntValue1 INT,
IntValue2 INT,
CharValue1 NVARCHAR(255),
CharValue2 NVARCHAR(255),
Date1 DATETIME,
Date2 DATETIME

我已经记不清有多少客户的系统依赖于这种可恶的东西了。

对于存储时间值,应该只使用UTC时区。不应使用当地时间。

像这样将冗余表连接到查询中:

select emp.empno, dept.deptno
from emp
join dept on dept.deptno = emp.deptno;