使用查找表

时间:2016-04-13 14:17:08

标签: sql sql-server lookup-tables

我尝试从单个MS SQL Server表中提取数据,该表使用nvarchar(MAX)作为几列的数据类型,并将其插入到使用int作为相应数据类型的表中nvarchar(MAX)数据。我有几个表(查找表?)来提供int值。

表格有以下设计:

MobileClientTable(源表)

enter image description here

LookupWeather

enter image description here

LookupArea

enter image description here

destinationTable会

enter image description here

一些示例数据:

MobileClientTable

enter image description here

LookupWeather

enter image description here

LookupArea

enter image description here

所以我喜欢的是Destination表中的行,如下所示:

ID   Area   Weather   Details
1    4      1         None

其中区域和天气的4和1已从查找表中获得。

我的SQL有点生疏,但我已经成功地获得了这个SQL声明:

USE [ETLTest]
GO

INSERT INTO DestinationTable(ID, Area, Weather, Details) VALUES 
    (
        (SELECT ID FROM dbo.MobileClientTable),
        (SELECT ID FROM dbo.LookupArea WHERE Area = dbo.MobileClientTable.Area),
        (SELECT ID FROM dbo.LookupWeather WHERE Weather = dbo.MobileClientTable.Weather,
        (SELECT AnyOtherDetails FROM dbo.MobileClientTable)
    );

当然,语法不正确。我收到以下错误:

Msg 156, Level 15, State 1, Line 6
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near ')'.
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near '+'.
Msg 102, Level 15, State 1, Line 9
Incorrect syntax near ')'.

我哪里错了?

2 个答案:

答案 0 :(得分:5)

values不是必需的,因为正在使用select

加入表格,将所需的值插入相应的列中。

INSERT INTO DestinationTable(ID, Area, Weather, Details)
SELECT mc.ID , a.id, w.id, mc.anyotherdetails
FROM dbo.MobileClientTable mc
join dbo.LookupWeather w on w.Weather = mc.Weather
join dbo.LookupArea a on a.Area = mc.Area

答案 1 :(得分:1)

INSERT INTO DestinationTable(ID, Area, Weather, Details)
    SELECT a.ID, b.Area, c.Weather, d.AnyOtherDetails 
    FROM dbo.MobileClientTable a
    JOIN dbo.LookupArea b ON a.Area=b.Area
    JOIN dbo.LookupWeather c ON c.Weather = a.Weather