2009年6月11日 星期四

ExcelImportDB(整筆新增)

取得excel資料
string strCon = @" Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + 檔案路徑+ ";Extended Properties='Excel 8.0;HDR=No;IMEX=1;'";
DataSet ds_excel = new DataSet();
OleDbConnection objConn = new OleDbConnection(strCon);
objConn.Open();
OleDbDataAdapter odda = new OleDbDataAdapter("Select * from [sheet1$]", objConn);
odda.Fill(excel , "Sheet1");
objConn.Close();

定義table的欄位及資料型態(直接複製db的table)
DataSet ds_org=new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
sqlconn.Open();
SqlCommand cmd_original = new SqlCommand(@"SELECT fields1,fields2,fields3,fields4......
FROM table", sqlconn);//參考的資料表

SqlDataAdapter sda = new SqlDataAdapter(cmd_original);
sda.Fill(ds_org, "ORG");

DataTable dt = ds_org.Tables[0].Copy();//將架構和資料型態複製給定義的dt

將excel資料新增到dt(縱向新增)
for (int i = 1; i < ds_excel.Tables[0].Columns.Count; i++)
{
row = dt.NewRow();
row["fields1"] = ds_excel.Tables[0].Rows[0][i].ToString();
row["fields2"] = ds_excel.Tables[0].Rows[2][i].ToString();
.......
dt.Rows.Add(row);
}

將資料新增至DB
SqlCommandBuilder builder = new SqlCommandBuilder(sda);
builder.RefreshSchema();

sda.Update(dt);

ds_excel.Dispose();
ds_org.Dispose();
sda.Dispose();
sqlconn.Close();

2009年6月10日 星期三

數值進行四捨六入五取雙的判斷

要呈現的結果:
1.4→1
1.6→2
1.5→2
2.5→2

ALTER FUNCTION [dbo].[FN_ChangeNumber](@money decimal(18,2))
RETURNS Int
AS

BEGIN
declare @intvalue int,@decimalvalue int,@retvalue int

--取整數和小數第一位
select @intvalue=substring(Convert(nvarchar(20),@money),1, charindex('.', Convert(nvarchar(20),@money))-1) , @decimalvalue=substring(substring(Convert(nvarchar(20),@money), charindex('.', Convert(nvarchar(20),@money))+1 , len(Convert(nvarchar(20),@money))-charindex('.', Convert(nvarchar(20),@money))) ,1,1)

if(@decimalvalue<=4)begin set @retvalue=@intvalue end

if(@decimalvalue>=6)begin set @retvalue=@intvalue+1 end

if(@decimalvalue=5)begin
if(@intvalue%2=0) set @retvalue=@intvalue
else set @retvalue=@intvalue+1
end

RETURN @retvalue
END

感謝Keen協助