SQL Server存储过程连接表ON T1.ID = mid(T2.valutation)

时间:2016-07-30 22:19:36

标签: sql-server tsql

我有车的部分T1,如下:

ID  Name
-------------
1   Tyres
2   Gearbox
3   Engine
4   Body
5   Brakes
6   ..
带有名为valutation的列的汽车列表

和T2,其中包含一串数字[0-9]

ID  Brand   Model   Color   Year    KKm     ....    valutation
---------------------------------------------------------------
1   Audi    A3      Green   2014    185             86354

valutation中的每个数字都是根据其在字符串中的位置引用汽车的一部分:即

8, since it is in position 1, refers to Tyres
6, since it is in position 2, refers to GearBox
...
4, since it is in position 5, refers to Brakes

等等

我需要构建一个返回此

的SQL Server存储过程
ID  Brand   Model   Color   Year    KKm     Tyres   GearBox   Engine   Body   Brakes
----------------------------------------------------------------------------------------
1   Audi    A3      Green   2014    185       8         6       3        5       4

我尝试了一些解决方案,但正如你从问题的(错误的)主题中看到的那样,我实际上并不知道需要哪种功能。

由于

2 个答案:

答案 0 :(得分:1)

您可以使用动态SQL来执行此操作。我没有访问SQL服务器所以无法检查这个,但我会这样做:

declare @sql varchar(200)
declare @i int

set @sql = 'select *'
set @i = 1

While @i <= (select count(*) from T1)
begin
  set @sql = @sql + ', substring(valuation,' + cast(@i as varchar(10)) + ',1) as ' + (select name from T1 where id = @i)
  set @i = @i + 1
end

set @sql = @sql + ' from T2'

exec(@sql)

(我已经复制了你对'估价'的明显拼写错误,也就是说,我认为你的表中拼写了'vutation'。)

答案 1 :(得分:0)

AS @dfundako指出,这是非常糟糕的设计,很可能会困扰你。

然而,与大多数节目一样,&#34;一切皆有可能&#34;。

所以,这是使用CTE的快速版本。

这不是动态版本,从某种意义上说,我正在从查找表中对您的标签进行硬编码。你可以从这里拿走它:

DECLARE @t TABLE(id int, Valuation VARCHAR(50))

INSERT INTO @t
    SELECT ID, Valuation FROM T2
;WITH cte AS
    (SELECT id, Valuation, SUBSTRING(Valuation, 1, 1) AS position_char, 1 AS ind FROM @t
     UNION ALL 
     SELECT id, Valuation, SUBSTRING(Valuation, ind + 1, 1) AS position_char, ind + 1 FROM cte WHERE LEN(Valuation) > ind
    )

SELECT T2.Model, T2.Brand, T2.Color, T2.valuation,
     p.[1] AS 'Tyres', [2] AS 'Gearbox', [3] AS 'Engine', [4] AS 'Body', [5] AS 'Brakes'
FROM cte 
PIVOT (MAX(position_char) 
    FOR ind IN([1],[2],[3],[4],[5])) p
INNER JOIN T1
    ON p.id = T1.ID
INNER JOIN T2
    ON T1.ID = T2.ID

Output

您想要的正确关系结构(如果可以更改)更像是以下内容:

Proper Structure