希望这张图表有意义......
问题是我在很多表中有很多列,如何在视图中获取所有列值,而不是每行都有ISNULL
?
(sql server 10.5)
ITEM
+------+
| ID |
|------|
| 1 |
| 2 |
| 3 |
+------+
LANGUAGE
+-------+---------+
| ID | Name |
|-------+---------|
| 1 | English |
| 2 | French |
+-------+---------+
Item Names
+----------+---------+------------+------------+
| ItemID | LangId | Name | Color |
|----------+---------+------------+------------|
| 1 | 1 | apple | red |
| 1 | 2 | pomme | rouge |
| 2 | 1 | orange | orange |
| 3 | 1 | bannana | yellow |
+----------+---------+------------+------------+
理想的观点
+----------+---------+------------+------------+
| ItemID | LangId | Name | Color |
|----------+---------+------------+------------|
| 1 | 1 | apple | red |
| 1 | 2 | pomme | rouge |
| 2 | 1 | orange | orange |
| 2 | 2 | orange | orange | <--- added automatically
| 3 | 1 | bannana | yellow |
| 3 | 2 | bannana | yellow | <--- added automatically
+----------+---------+------------+------------+
因为我正在尝试创建视图,因此存在某些限制:
视图中要修改的列必须直接引用表列中的基础数据。无法以任何其他方式派生列,例如通过以下方式:
中间观点:
+----------+---------+------------+------------+
| ItemID | LangId | Name | Color |
|----------+---------+------------+------------|
| 1 | 1 | apple | red |
| 1 | 2 | pomme | rouge |
| 2 | 1 | orange | orange |
| 3 | 1 | bannana | yellow |
+----------+---------+------------+------------+
以及:
+----------+---------+------------+------------+
| ItemID | LangId | Name | Color |
|----------+---------+------------+------------|
| 1 | 1 | apple | red |
| 1 | 2 | pomme | rouge |
| 2 | 1 | orange | orange |
| 2 | 2 | - | - |
| 3 | 1 | bannana | yellow |
| 3 | 2 | - | - |
+----------+---------+------------+------------+
这些是一些观点:
view1 - 所有组合
view2 - 与语言的所有组合
相应的SQL:
SELECT dbo.view1.ItemID, dbo.view1.LanguageID, dbo.ItemLanguages.Name, dbo.ItemLanguages.Color
FROM dbo.ItemLanguages RIGHT OUTER JOIN
dbo.view1 ON dbo.ItemLanguages.LanguageID = dbo.view1.LanguageID AND dbo.ItemLanguages.ItemID = dbo.view1.ItemID
观点结果2
这是包含视图和表格的测试数据库:http://pastebin.com/4BpBSmHY
答案 0 :(得分:0)
我能够做到的一种方法是使用ISNULL
SELECT dbo.view1.ItemID,
dbo.view1.LanguageID,
ISNULL(dbo.ItemLanguages.Name,
(SELECT TOP (1) Name
FROM dbo.ItemLanguages AS x
WHERE (ItemID = dbo.view1.ItemID))) AS Name,
ISNULL(dbo.ItemLanguages.Color,
(SELECT TOP (1) Color
FROM dbo.ItemLanguages AS x
WHERE (ItemID = dbo.view1.ItemID))) AS Color,
CASE
WHEN dbo.ItemLanguages.ItemID is NULL THEN 1
ELSE 0
END as valid
FROM dbo.ItemLanguages RIGHT OUTER JOIN
dbo.view1 ON dbo.ItemLanguages.ItemID = dbo.view1.ItemID
AND dbo.ItemLanguages.LanguageID = dbo.view1.LanguageID
我不喜欢这种方法的原因是我在更多专栏中这样做。我认为做多个SELECTS会大大减慢结果。
我虽然能够检查该行是否与CASE
一样存在
然后调用select一次并填充所有列
WHEN dbo.ItemLanguages.ItemID is NULL THEN 1
ELSE 0
END as valid
..在视图中