遍历SQL文件中的
问题描述:
我有一个看起来像这样(显然是真实的东西是有点长,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文件(或文件)。但我不太清楚如何来解决这个问题...
干杯
答
通常你应该更喜欢设置的解决方案。我不知道的完整的解决方案会是什么样子,但是从一开始,你已经给:
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以这种方式更好地工作。
答
在过度简化的东西在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);
}
}
}
答
有关于如何从通过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
你可以导入使用SQL Server的导入向导的文件,然后脚本中的值,无论你需要他们算账。 – Bridge 2012-08-15 08:19:29
作为桥说,或者您可以使用脚本语言(猛砸/ PHP /拼音/ Python或任何你熟悉的),将阅读列表,生成文件,运行该文件,并进行处理。 – 2012-08-15 08:20:46