2017-04-10 59 views
0

我試圖運行下面的查詢:在計算列爲什麼不能用一個case語句中的子查詢

create table MyTable (
    TableIndex bigint primary key identity(1,1) not null, 
    ForeignKey1 int not null, 
    ForeignKey2 char(16) not null, 
    fldSomeNumber float(24), 
    fldScore as cast(case 
      when fldSomeNumber is null or fldCSIPercentage=0 then 0 
      when fldSomeNumber <= 0.09 then (select fldTenthScore from tblScores where ScorePrimaryKey=MyTable.ForeignKey2) 
      when fldSomeNumber <= 0.9 then (select fld1Score from tblScores where ScorePrimaryKey=MyTable.ForeignKey2) 
      ... 
      else 100 end as float(24)) 
); 

但我不斷收到以下錯誤:「子查詢不允許在這種情況下,只允許標量表達式。「是否不可能將子選擇放入像這樣的計算列中?

我運行的SQL Server Express 2016

回答

1

你真的不能做你的要求在所有與一個表是什麼,你要使用視圖,並把計算列上視圖。

這樣一種觀點認爲會是這個樣子

CREATE VIEW MyView AS 

SELECT 
cast(case 
      when fldSomeNumber is null or fldCSIPercentage=0 then 0 
      when fldSomeNumber <= 0.09 then tblScores.fldTenthScore 
      when fldSomeNumber <= 0.9 then tblScores.fld1Score 
      ... 
      else 100 end as float(24)) AS fldScore 
FROM 
MyTable 
INNER JOIN tblScores 
ON tblScores.ScorePrimaryKey = MyTable.ForeignKey2 

見第二回答這個問題:

formula for computed column based on different table's column

0

當您使用CREATE TABLE,你必須使用列名和數據類型但是在這裏,當您寫入fldScore列名稱時,將插入一個值而不是數據類型。因爲CASE結構返回一個值,並且您只將該值作爲浮點數轉換。

但是,如果您的意思是計算列,則只能使用當前表中的列來定義不是從其他表中的計算列。

+0

它的意思是不具有指定的數據類型計算列。 – mallan1121

0

與函數(所推薦的mallan1121)來解決這個問題的方法如下:

IF EXISTS (
    SELECT * FROM sysobjects WHERE id = object_id('fnCalculateScore') 
    AND xtype IN ('FN', 'IF', 'TF') 
) 
    DROP FUNCTION fnCalculateScore 
go 

create function fnCalculateScore (
    @SomeNumber float(24), 
    @SomeKey char(16) 
) 
returns float(24) 
with schemabinding 
as 
begin 
    return (select case 
      when @SomeNumber is null or @SomeNumber=0 then 0 
      when @SomeNumber <= 0.09 then (select fldTenthScore from dbo.tblScores where [email protected]) 
      when @SomeNumber <= 0.9 then (select fld1Score from dbo.tblScores where [email protected]) 
      ... 
      else 100 end as float(24)) 
end 
go 

create table MyTable (
    TableIndex bigint primary key identity(1,1) not null, 
    ForeignKey1 int not null, 
    ForeignKey2 char(16) not null, 
    fldSomeNumber float(24), 
    fldScore as dbo.fnCalculateScore(fldSomeNumber, ForeignKey2) 
);