2012-08-15 119 views
0

我有一個看起來像這樣(顯然是真實的東西是有點長,actualy做的東西:))的SQL文件遍歷SQL文件中的

DECLARE @Mandatory int = 0 
DECLARE @Fish int = 3 

DECLARE @InitialPriceID int 
if @Mandatory= 0 
    begin 
    select @InitialPriceID = priceID from Fishes where FishID = @Fish 
    end 

命令我的文件「強制性」和「魚」值

Mandatory,Fish 
    1,3 
    0,4 
    1,4 
    1,3 
    1,7 

我需要編寫一個程序,將產生對我們的DBO對數據庫運行SQL文件(或文件)。但我不太清楚如何來解決這個問題...

乾杯

+0

你可以導入使用SQL Server的導入嚮導的文件,然後腳本中的值,無論你需要他們算賬。 – Bridge 2012-08-15 08:19:29

+0

作爲橋說,或者您可以使用腳本語言(猛砸/ PHP /拼音/ Python或任何你熟悉的),將閱讀列表,生成文件,運行該文件,並進行處理。 – 2012-08-15 08:20:46

回答

1

通常你應該更喜歡設置的解決方案。我不知道的完整的解決方案會是什麼樣子,但是從一開始,你已經給:

declare @Values table (Mandatory int,Fish int) 
insert into @Values(Mandatory,Fish) values 
(1,3), 
(0,4), 
(1,4), 
(1,3), 
(1,7), 

;with Prices as (
    select 
     Mandatory, 
     Fish, 
     CASE 
      WHEN Mandatory = 0 THEN f.PriceID 
      ELSE 55 /* Calculation for Mandatory = 1? */ 
     END as InitialPriceID 
    from 
     @Values v 
      left join /* Or inner join? */ 
     Fishes f 
      on 
       v.Fish = f.Fish 
) select * from Prices 

你的目標應該計算所有的結果一氣呵成,而不是「環通」努力每次計算。 SQL以這種方式更好地工作。

1

在過度簡化的東西在C#或類似的,你可以使用字符串處理方法的風險:

class Program 
{ 
    static void Main(string[] args) 
    { 
     var sb = new StringBuilder(); 

     foreach(var line in File.ReadLines(@"c:\myfile.csv")) 
     { 
      string[] values = line.Split(','); 

      int mandatory = Int32.Parse(values[0]); 
      int fish = Int32.Parse(values[1]); 

      sb.AppendLine(new Foo(mandatory, fish).ToString()); 
     } 

     File.WriteAllText("@c:\myfile.sql", sb.ToString()); 
    } 

    private sealed class Foo 
    { 
     public Foo(int mandatory, int fish) 
     { 
      this.Mandatory = mandatory; 
      this.Fish = fish; 
     } 

     public int Mandatory { get; private set; } 
     public int Fish { get; set; } 

     public override string ToString() 
     { 
      return String.Format(@"DECLARE @Mandatory int = {0} 
DECLARE @Fish int = {1} 

DECLARE @InitialPriceID int 
if @Mandatory= 
begin 
select @InitialPriceID = priceID from Fishes where FishID = @Fish 
end 
", this.Mandatory, this.Fish); 
     } 
    } 
}