【问题标题】:Loop over SQL commands in a file循环文件中的 SQL 命令
【发布时间】:2012-08-15 08:15:30
【问题描述】:

我有一个看起来像这样的 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 文件以针对数据库运行。但我不太确定如何解决这个问题......

干杯

【问题讨论】:

  • 您可以使用 SQL Server 的导入向导导入文件,然后将值编写到您需要的任何位置。
  • 正如 Bridge 所说,或者您可以使用脚本语言(Bash/PHP/Ruby/Python 或任何您熟悉的语言)来读取列表、生成文件、运行文件并扔掉它。

标签: sql sql-server


【解决方案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 以这种方式工作得更好。

【讨论】:

    【解决方案2】:

    冒着过度简化 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);
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      有很多关于如何通过t-sql从文本文件中读取的文章,查看"Stored Procedure to Open and Read a text file" on SO,如果你可以将输入文件的格式更改为xml,那么你可以查看SQL SERVER – Simple Example of Reading XML File Using T-SQL

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-16
        • 1970-01-01
        • 1970-01-01
        • 2019-11-05
        • 2020-09-29
        • 1970-01-01
        • 2022-11-02
        • 1970-01-01
        相关资源
        最近更新 更多