0

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

干杯

4

3 回答 3

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

于 2012-08-15T08:22:52.920 回答
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);
        }
    }
}
于 2012-08-15T08:25:12.947 回答
1

有很多关于如何通过 t-sql 从文本文件中读取的文章,请查看 SO 上的“打开和读取文本文件的存储过程”,如果您可以将输入文件的格式更改为 xml,那么您可以查看SQL SERVER - 使用 T-SQL 读取 XML 文件的简单示例

于 2012-08-15T08:25:50.437 回答