asp.net、mvc、ajax、js、jquery、sql、EF、linq、netadvantage第三方控件知識點筆記

很簡單,以下:javascript

父頁面:(彈出提示框)css

 function newwindow(obj)html

{java

 var rtn = window.showModalDialog('NewPage.htm','','status=no,scrollbars=no,top=20,left=110,width=420,height=165');node

 var div = document.getElementById("div1");mysql

 div.innerHTML=rtn;jquery

}web

子頁面:ajax

function pageinit()正則表達式

{

var lab = document.getElementById("infoimage");

window.returnValue=lab.value;

window.close();

}

---------------------------父窗體

  function Show()

    {

      var bb=2;

      var a=window.showModalDialog("彈出2.aspx","","dialogwidth=500px;dialogheight=500px;");

      document.getElementById("Text1").value=a;

    }

-----------------------------子窗體

function Button1_onclick() {

  var a=document.getElementById("TextBox1");

  window.returnValue=a.value;

  window.close();

------------------window.dialogArguments

}

-------------------------------------------------後臺調用前臺js函數;

 ClientScript.RegisterStartupScript(ClientScript.GetType(), null, "<script>guo('fffff');</script>");

--------------------------sd可使name,或者是Id;

 document.all("sd").style["height"]=h;//設置樣式,js控制樣式

-------------------------調節透明度

    <style type="text/css">

#guo {

         filter:alpha(opacity=50);

}

</style>

--------------------------------調用客戶端事件:

  ScriptManager.RegisterStartupScript(UltraWebGrid1, typeof(UltraWebGrid), "null", "<script>window.parent.gb('T');</script>", false);

---------------調用frame框架外的函數:

<script>window.parent.gb('T');</script>", false)

------------------iframe獲取父頁面的元素

 window.parent.document.getElementById("Text1").value="hahhahhaha";

父親獲取兒子

JS版:document.getElementById("IframeID").contentWindow.document.getElementById("divID")

--------------------------------js星期:

  var day=["日","一","二","三","四","五","六",];

  document.write("星期"+day[new Date().getDay()]);

-----------------------------------

        Infragistics.WebUI.UltraWebListbar.UltraWebListbar bar = new Infragistics.WebUI.UltraWebListbar.UltraWebListbar();

        bar.ID = "menu";

        bar.SkinID = "MenuBar";

        bar.ApplyStyleSheetSkin(Page);

        //bar.Width=

        //bar.Height = "100%";

        bar.Groups.Clear();

        YongHuModel userModel= Session["LoginUser"] as YongHuModel;

        int roleId = userModel.RoleId.Id;

        IList<RoleLines> roleLines = RoleLinesManager.GetSYSMenu(roleId);

 

        foreach (RoleLines roleItem in roleLines)

        {

            if (roleItem.LinkId.ParentId == 0)

            {

                //Infragistics.WebUI.UltraWebNavigator.Node root = new Node();

                //root.Text = roleItem.LinkId.Name;

                //root.DataKey = roleItem.LinkId.Id;

                //root.Expanded = true;

                //root.ImageUrl = "~/XtGlMk/images/base.gif";

 

                TreeNode root = new TreeNode();

                root.Text = roleItem.LinkId.Name;

                root.Value = roleItem.LinkId.Id.ToString();

                root.Expanded = true;

                root.NavigateUrl = "";

                Infragistics.WebUI.UltraWebListbar.Group group = new Infragistics.WebUI.UltraWebListbar.Group(root.Text);

 

 

                MyTemplate tem = new MyTemplate();

                tem.Lines = roleLines;

                tem.Root = root;

 

                group.Template = tem;

                bar.Groups.Add(group);

            }

        }

        bar.DataBind();

        Panel1.Controls.Add(bar);

----------------------------------------------------treeNode節點添加:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Collections.Generic;

using JC.BLL;

using JC.Model;

/// <summary>

/// MyTemplate 的摘要說明

/// </summary>

public class MyTemplate : ITemplate

{

    private IList<RoleLines> lines;

    public IList<RoleLines> Lines

    {

        set { lines = value; }

    }

    private TreeNode root;

    public TreeNode Root

    {

        set { root = value; }

    }

    private System.Web.UI.Page skin;

    public System.Web.UI.Page Skin

    {

        set { skin = value; }

    }

    public void InstantiateIn(Control container)

    {

        TreeView tree = new TreeView();

        tree.Target = "I3";

        //tree.Font.Size = FontUnit.Point(9);

        //tree.ForeColor = System.Drawing.Color.Black;

 

        //tree.ImageSet = TreeViewImageSet.BulletedList;

        tree.NoExpandImageUrl = "../images/left.gif";

        //tree.Font.Size = FontUnit.Point(9);

        tree.CssClass = "STYLE3";

 

        tree.Nodes.Add(root);

        FillTemp(root, Convert.ToInt32(root.Value));

 

        //test

        //TreeNode cNode = new TreeNode();

        //cNode.Text = "租賃";

        //cNode.NavigateUrl = "~/XmGlMk/TenancyManager/Tenancy.aspx";

        //cNode.Target = "I3";

 

 

        //TreeNode gNode = new TreeNode();

        //gNode.Text = "還租";

        //gNode.NavigateUrl = "~/XmGlMk/TenancyManager/GiveBackManager.aspx";

        //gNode.Target = "I3";

        //tree.Nodes.Add(cNode);

        //tree.Nodes.Add(gNode);

        tree.DataBind();

        container.Controls.Add(tree);

    }

    /// <summary>

    /// 使用遞歸算法添加節點

    /// </summary>

    /// <param name="root"></param>

    /// <param name="parentNodeId"></param>

    private void FillTemp(TreeNode root, int parentNodeId)

    {

        foreach (RoleLines entity in lines)

        {

            if (entity.LinkId.ParentId == parentNodeId)

            {

                TreeNode node = new TreeNode();

                node.Target = "I3";

                node.Text = entity.LinkId.Name;

                node.NavigateUrl = entity.LinkId.Url;

                node.Value = entity.LinkId.Id.ToString();

                string xtbh = HttpContext.Current.Session["XmBH"] as string;

                if (xtbh != null)

                {

                    int bh = Convert.ToInt32(xtbh);

                    XiangMuModel xm = XiangMuManager.getXiangMuByBH(bh);

                    if (!xm.JiJiaB)

                    {

                        if (entity.LinkId.Id == 30107)

                        {

                            node.NavigateUrl = "~/XmGlMk/YiDongJiJia.aspx";

                        }

                    }

                    DJConfiguration config = Commond.GetDjConfiguration(DJTYPE.RKD);

                    if (!config.GFSL)

                    {

                        if (node.Value == "30201" || node.Value == "30202" || node.Value == "30203" || node.Value == "30204")

                        {

                            continue;

                        }

                    }

                }

                FillTemp(node, entity.LinkId.Id);

                root.ChildNodes.Add(node);

            }

        }

    }

}

---------------------------------------listbar:

        Infragistics.WebUI.UltraWebListbar.Group group = new Infragistics.WebUI.UltraWebListbar.Group("aa");

        Infragistics.WebUI.UltraWebListbar.Item ite1 = new Infragistics.WebUI.UltraWebListbar.Item();

        ite1.Text = "aaaa";

        group.Items.Add(ite1);

        this.UltraWebListbar1.Groups.Add(group);

----------------------------------------

 ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "Button2",

                   "<script>alert('請選擇要刪除的行!');</script>", false);

------------------------------------------scriptmanage中使用控件netadvantage可以使用;webconfig文件

  <httpHandlers>

      <remove path="*.asmx" verb="*"/>

      <add path="ScriptResource.axd" verb="GET,HEAD" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>

  </httpHandlers>

---------------------------

  <p style="padding-top:5px;">歡迎您</p> 若換成<span>就很差用了;

------------------------viewstate相似於static

-------------------------分頁:

string sql2 = "select top " + page.PageSize + " * from GongSi where BH not in(select top " + page.Start + " BH from GongSi)";

---------------------------gridview中添加控件

 <igtbl:TemplatedColumn  Width="200px">

                    <HeaderTemplate>

                        操做

                    </HeaderTemplate>

                    <CellTemplate>

                        <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click" Width="80px">下屬用戶</asp:LinkButton>

                    </CellTemplate>

                    <Header>

                        <RowLayoutColumnInfo OriginX="3" />

                    </Header>

                    <Footer>

                        <RowLayoutColumnInfo OriginX="3" />

                    </Footer>

                </igtbl:TemplatedColumn>

---------------------------------------------------------------------------------獲取gridview的表格值,cell值:

  Session["Id"] = UltraWebGrid1.DisplayLayout.SelectedCells[0].Row.Cells[0];

 Session["Id"] = UltraWebGrid1.DisplayLayout.SelectedRows[0].Cells[0].ToString();

   案例:

   if (UltraWebGrid2.DisplayLayout.SelectedCells[0] != null)

        {

            if (UltraWebGrid2.DisplayLayout.SelectedCells[0].Row != null)

            {

                int id = Convert.ToInt32(UltraWebGrid2.DisplayLayout.SelectedCells[0].Row.Cells[0].Text);

                Session["XgGsID"] = id;

                Response.Redirect("XgGongSi.aspx");

            }

            else

            {

                ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "Button2",

                   "<script>alert('請選擇要修改的行!');</script>", false);

            }

        }

        else

        {

            if (UltraWebGrid2.DisplayLayout.SelectedRows[0] != null)

            {

                int id = Convert.ToInt32(UltraWebGrid2.DisplayLayout.SelectedRows[0].Cells[0].Text);

                Session["XgGsID"] = id;

                Response.Redirect("XgGongSi.aspx");

            }

            else

            {

                ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "Button2",

                      "<script>alert('請選擇要修改的行!');</script>", false);

            }

        }

-------------------------------------------------------------------------------------------

 

----------------listbox添加項:

 foreach (YongHuModel model in yhgl_models)

            {

                ListItem li = new ListItem();

                li.Text = model.MC.ToString();

                li.Value = model.BH.ToString();

                cblJZXM.Items.Add(li);

            }

------------------------------------------------listbox:添加移除列;

  cblJZXM.Items.Add(li);

                //移除

cblXM.Items.RemoveAt(i);

------------------------------------------------彈出框案例:

父頁面案例:彈出提示框

<script language="javascript" type="text/javascript">

function Button1_onclick() {

   window.showModalDialog("子.aspx",this,"dialogHeight:450px;dialogWidth:800px;status=no");

}

function show(str)

{

  document.getElementById("Text1").value=str;

}

</script>

//子頁面案例:後臺---

 ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "null",

           "<script>window.dialogArguments.addgs('" + GYSBH + "','" + MC + "');window.close();</script>", false);

必須在head內添加:

<base target = "_self"/>

-----------------------------------後臺獲取前臺session值:

 string dataBaseName=System.Web.HttpContext.Current.Session["XmName"].ToString();

//--------------------------------------查詢某數據庫某個表:

SELECT * FROM CC ..AA

------------------------------------------

cmd.Parameters.AddRange(values);//循環添加sqlparameters

-----------------------------------------------------------------

 using(SqlDataReader sdr=DBHelper.GetReader(sql1)),使用using的前提是對象類必須是實現:Idispose接口;

            {

                if (sdr.Read())

                {

                    return 0;

                }

            }

--------------------------------------------------------------------------------------------------前臺:

  function IfGoDel(bh)

        {

          if(confirm("是否同時刪除合格供應商名冊與供應商複覈裏的數據?"))

          {

            document.getElementById("hidCommond").value="allDel";

            document.getElementById("hidXtBH").value=bh;

           

          }else

          {

            document.getElementById("hidCommond").value="Only";

            document.getElementById("hidXtBH").value=bh;

          }

//          __doPostBack("UpdatePanel1","");

         document.form1.submit();

        }

--------後臺:

  string commond = Request.Form["hidCommon"];

            if (commond == "Search")

            {

                Bind(1);

            }

            string commd = Request.Form["hidCommond"];

            string xtbh = Request.Form["hidXtBH"];

            if (commd == "allDel")

            {

                int key = Convert.ToInt32(xtbh);

                bool bb = GysFpManager.dropGysFPByBH(key);

                if (bb)

                    {

 

                        ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "Button2",

                           "<script>alert('刪除成功!');</script>", false);

                        Bind(1);

                    }

                    else

                    {

                        ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "Button2",

                           "<script>alert('刪除失敗!');</script>", false);

                    }

             

            }

            if (commd == "Only")

            {

                return;

            }

        }

    }

-----------------------------------數據庫分頁;

   List<GysModel> GysS = new List<GysModel>();

            List<SqlParameter> pars = new List<SqlParameter>();

            string searchSql = CreatSql(searchModel, pars);

            string selectCount = "select count(*) from Gys where  (FHJG=1 or FHJG is null ) " + searchSql;

            page.TotalRow = Convert.ToInt32(DBHelper.GetScalar(selectCount, pars.ToArray()));

            StringBuilder sql = new StringBuilder("select * from (select  row_number() OVER (ORDER BY BH desc) AS rowId,* from Gys where  (FHJG=1 or FHJG is null )");

            sql.Append(searchSql).Append(")as Temp where rowId between ").Append(page.Begin).Append(" and ").Append(page.End);

            using (SqlDataReader dr = DBHelper.GetReader(sql.ToString(), pars.ToArray()))

            {

                while (dr.Read())

----------------------------------------添加事務:

begin transaction

insert into A(c1,c2) values(v1,v2);

insert into B(c3,c4) values(v3,v4);

insert into C(c5,c6) values(v5,v6);

if @@ERROR = 0

begin

     commit transaction;

end

else

begin

    rollback transaction;

end

---------------------------這條語句是正確的

 cn = new SqlConnection("data source=DELL-PC\\AA;uid=sa;pwd=sa");

            cn.Open();

            StringBuilder sb = new StringBuilder(" use CC update [User] set UName='666' where UId="+i+"");

-----------------------------這條語句也是正確的;

 cn = new SqlConnection("data source=DELL-PC\\AA;initial catalog=CC; uid=sa;pwd=sa");

            cn.Open();

            StringBuilder sb = new StringBuilder(" use CD update [User] set UName='666' where UId="+i+"");

---------------------------------同時對兩個數據庫進行操做

 try

        {

            int i = 1;

            cn = new SqlConnection("data source=DELL-PC\\AA;initial catalog=CC; uid=sa;pwd=sa");

            cn.Open();

            StringBuilder sb = new StringBuilder("begin transaction ");

            sb.Append("use CC update [User] set UName='xiao' where UId=1");

            sb.Append("use CD update [User] set UName='xiao' where UId=1");

            sb.Append("if @@ERROR = 0 begin commit transaction end else begin rollback transaction end");

            SqlCommand cmd = new SqlCommand(sb.ToString(), cn);

            cmd.ExecuteNonQuery();

        }

------------------------------

cmd.Parameters.AddRange(values);

--------------------------------------

  List<GysFhModel> GysFhS = new List<GysFhModel>();

            List<SqlParameter> pars = new List<SqlParameter>();

            string searchSql = CreatSql(searchModel, pars);

            string selectCount = "select count(*) from GYSFH left join GYS  on GYSFH.GYSBH=GYS.BH where  1=1 " + searchSql;

            page.TotalRow = Convert.ToInt32(DBHelper.GetScalar(selectCount, pars.ToArray()));

            StringBuilder sql = new StringBuilder("select * from (select  row_number() OVER (ORDER BY GYSFH.BH desc) AS rowId,GYSFH.* ,GYS.MC from GYSFH left join GYS  on GYSFH.GYSBH=GYS.BH where 1=1 ");

            sql.Append(searchSql).Append(")as Temp where rowId between ").Append(page.Begin).Append(" and ").Append(page.End);

 

------------------------javascript:後臺提交

  document.getElementById("HiddenField1").value="1233434";

         var b=document.getElementById("HiddenField2");

         window.form1.submit();

 

   接收 if (IsPostBack)

        {

            TextBox1.Text = HiddenField1.Value.ToString();

        }

------------------------將數據庫備份到指定位置;

backup database cc to disk='D:\d3.bak'

-----------------------將備份還原到某個位置並附加數據庫:格式不能變化;

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

restore database SJCL33 from disk='D:\Company\通用版\JC.Web\File\BakSource\TSSJCL.bak' with FILE = 1, move 'SJCL' to 'C:\Users\dell\Desktop\s\SJCL33.mdf',move 'SJCL_Log' to 'C:\Users\dell\Desktop\s\SJCL33.LDF',NOUNLOAD,  REPLACE,  STATS = 10

---------------------------

 document.write("瀏覽器名稱: " + navigator.appName + "<br>");

 

        document.write("版本號: " + navigator.appVersion + "<br>");

 

        document.write("代碼名字: " + navigator.appCodeName + "<br>");

 

        document.write("用戶代理標識: " + navigator.userAgent);

---------------------------bit類型數據存儲

插入時能夠存:

INSERT INTO Users(Sex) VALUES('TRUE');

0爲false,1爲true;

或者直接插入0或1;插入時除了整形不帶單引號其他都帶;

顯示時也爲True或false;

-----------------------------存儲過程整形做爲條件

ALTER PROCEDURE dbo.selectuser

(

     @UId int,

     @result nvarchar(20) output

)

AS

 declare @s nvarchar(100)

 set @s=@UId

 declare @str nvarchar(1000)

 set @str='select @result=UName from [User] where UId='''+@s+''''//一個或是三個單引號都行;如果整形,先賦值給字符型就好了

EXEC sp_executesql @str, N'@result nvarchar(20) OUTPUT', @result OUTPUT

--------------------------------數據庫分頁存儲過程

"select UName from [User] where UName like '%"+ss+"%'"

ALTER PROCEDURE dbo.SelectPages

  (

     @name int,

          @pageSize         INT,              --每頁顯示的索引號

         @pageIndex        INT,               --每頁顯示的記錄數

         @count      INT OUTPUT        --總記錄數

  )

AS

  begin

  declare @na nvarchar(20)

  set @na=@name

    declare @sqlstrc nvarchar(2000)

         declare @sqlstrd nvarchar(2000)

         set @sqlstrc='select @count=count(*) from Fen where Name>'''+@na+''''

         exec sp_executesql @sqlstrc, N'@count int output',@count output

         set @sqlstrd='select Name from (select Name,ROW_NUMBER() OVER (ORDER BY Id) AS SerialNumber from Fen where Name>'''+@na+''') as t'

         set @sqlstrd=@sqlstrd+' WHERE t.SerialNumber > ' + CONVERT(NVARCHAR(100), (@pageIndex - 1) * @pageSize) +

                   ' AND t.SerialNumber <= ' + CONVERT(NVARCHAR(100), @pageIndex * @PageSize)

    exec (@sqlstrd)

  end

----------------------------------數據庫備份,斷開鏈接知識

using System;

using System.Collections.Generic;

using System.Text;

using System.Data;

using System.Data.SqlClient;

using JC.Model;

namespace JC.DAL

{

    public class DataBaseService

    {

        private const string SQL_SELECT_DATABASE_INFO = "select name,filename,fileid from sysfiles ORDER BY fileid";

        private const string SQL_SELECT_SYSPROCESS = "select * from master..sysprocesses where dbid=db_id(@AimDB)";

        private const string SQL_KILL_PROCESS_PRO = "killspid";

        private const string SQL_RESTORE = "restore database {0} from disk=@SourceDbBakPath with FILE = 1, move @DBName to @DBPath,move @DBLogName to @DBLogPath,NOUNLOAD,  REPLACE,  STATS = 10";

        private const string SQL_EXITS_PROC = "select * from sysobjects where id = object_id(@ProName) and OBJECTPROPERTY(id, N'IsProcedure') = 1";

        /// <summary>

        /// 獲取mdf文件的基本信息

        /// </summary>

        /// <returns></returns>

        public static List<DataBaseModel> GetDataBaseInfo()

        {

            List<DataBaseModel> list = new List<DataBaseModel>();

            using (SqlDataReader reader = DBHelper.GetReader(SQL_SELECT_DATABASE_INFO))

            {

                while(reader.Read())

                {

                    DataBaseModel model = new DataBaseModel();

                    model.Fileid = Convert.ToInt32(reader["fileid"]);

                    model.DataBaseName = reader["name"].ToString();

                    model.DataBasePath = reader["filename"].ToString();

                    list.Add(model);  

                }

                reader.Close();

            }

            return list;

        }

        /// <summary>

        /// 判斷存儲過程是否存在於master數據庫

        /// </summary>

        /// <param name="proName">存儲過程名稱</param>

        /// <returns></returns>

        public static bool ExitsPro(string proName)

        {

            bool result = false;

            using (SqlDataReader reader = DBHelper.GetReaderByConMaster(CommandType.Text, SQL_EXITS_PROC, new SqlParameter("@ProName", proName)))

            {

                if (reader.Read())

                {

                    result = true;

                }

                reader.Close();

            }

            return result;

        }

        /// <summary>

        /// 判斷指定數據庫是否有鏈接進程

        /// </summary>

        /// <param name="aimDbBase">數據庫名稱</param>

        /// <returns></returns>

        public static bool ExitsProcess(string aimDbBase)

        {

            bool result = false;

            using (SqlDataReader reader = DBHelper.GetReader(SQL_SELECT_SYSPROCESS, new SqlParameter("@AimDB", aimDbBase)))

            {

                if (reader.Read())

                {

                    result = true;

                }

                reader.Close();

            }

            return result;

        }

        /// <summary>

        /// 判斷某數據庫是否有訪問進程,有就關閉全部相關進程

        /// </summary>

        /// <param name="aimDbBase">數據庫名稱</param>

        /// <returns></returns>

        public static int ExitsKillProcess(string aimDbBase)

        {

            return DBHelper.ExecuteNonQueryByMaster(CommandType.StoredProcedure, SQL_KILL_PROCESS_PRO, new SqlParameter("@dbname", aimDbBase));

        }

        /// <summary>

        /// 數據庫備份

        /// </summary>

        /// <param name="sourceDbName">源數據庫名稱</param>

        /// <param name="aimDbPath">備份文件目標路徑</param>

        /// <returns></returns>

        public static int DbBackUp(string sourceDbName, string aimDbPath)

        {

            string sql = "BACKUP DATABASE " + sourceDbName + " TO DISK=@AimDbPath";

            return DBHelper.ExecuteNonQueryByMaster(CommandType.Text, sql, new SqlParameter("@AimDbPath",aimDbPath));

        }

        ///// <summary>

        ///// 數據庫還原

        ///// </summary>

        ///// <param name="aimDbName">目標數據庫名稱</param>

        ///// <param name="sourceDbBakPath">數據庫備份文件</param>

        ///// <returns></returns>

        //public static int DbRestore(string aimDbName, string sourceDbBakPath)

        //{

        //    string sql = "killspid @AimDbName restore database " + aimDbName + " from disk=@SourceDbBakPath with replace";

        //    SqlParameter [] pars=new SqlParameter[]{

        //    new SqlParameter("@AimDbName",aimDbName),

        //    new SqlParameter("@SourceDbBakPath",sourceDbBakPath)

        //    };

        //   return DBHelper.ExecuteNonQueryByMaster(CommandType.Text, sql, pars);

        //}

        /// <summary>

        /// 數據庫還原

        /// </summary>

        /// <param name="aimDbName">目標數據庫名稱</param>

        /// <param name="sourceDbBakPath">備份文件物理路徑</param>

        /// <param name="DBName">備份文件數據庫文件的邏輯名稱</param>

        /// <param name="DBPath">目標數據庫文件的物理路徑</param>

        /// <param name="DBLogName">備份文件記錄的源數據庫的數據庫日誌文件邏輯名</param>

        /// <param name="DBLogPath">目標數據庫日誌文件的物理路徑</param>

        /// <returns></returns>

        public static int DbRestore(string aimDbName, string sourceDbBakPath,string DBName,string DBPath,string DBLogName,string DBLogPath)

        {

           

            string sql = string.Format(SQL_RESTORE, aimDbName);

            SqlParameter[] pars = new SqlParameter[] {

            new SqlParameter("@SourceDbBakPath",sourceDbBakPath),

            new SqlParameter("@DBName",DBName),

            new SqlParameter("@DBPath",DBPath),

            new SqlParameter("@DBLogName",DBLogName),

            new SqlParameter("@DBLogPath",DBLogPath)

            };

             DBHelper.ExecuteNonQueryByMaster(CommandType.Text, sql, pars);

             return Convert.ToInt32(DBHelper.TestCommond("use " + aimDbName + " SELECT count(*) FROM sysobjects WHERE xtype = 'U'", null));

        }

        /// <summary>

        /// 建立斷開鏈接進程的存儲過程

        /// </summary>

        /// <returns></returns>

        public static int CreatKildPro()

        {

               string kill = "  CREATE proc killspid (@dbname varchar(20))";

                kill += " as ";

                kill += " begin ";

                kill += " declare @sql   nvarchar(500) ";

                kill += " declare @spid  int ";

                kill += " set @sql='declare getspid cursor for select spid from sysprocesses where dbid=db_id('''+@dbname+''')'";

                kill += " exec (@sql) ";

                kill += " open getspid  ";

                kill += " fetch next from getspid into @spid   ";

                kill += " while @@fetch_status <> -1   ";

                kill += " begin";

                kill += " exec('kill '+@spid) ";

                kill += " fetch next from getspid into @spid    ";

                kill += " end       ";

                kill += " close getspid  ";

                kill += " deallocate getspid  ";

                kill += " end";

              return  DBHelper.ExecuteNonQueryByMaster(CommandType.Text, kill, null);

        }

    }

}

---------------

using System.Configuration; string _connectionString = ConfigurationManager.AppSettings["ConnectionString"];  

--------------------------------------------動軟加密解密

using System;

using System.Security.Cryptography; 

using System.Text;

namespace Maticsoft.DBUtility

{

         /// <summary>

         /// DES加密/解密類。

         /// </summary>

         public class DESEncrypt

         {

                   public DESEncrypt()

                   {       

                  

                   }

 

                   #region ========加密========

 

        /// <summary>

        /// 加密

        /// </summary>

        /// <param name="Text"></param>

        /// <returns></returns>

                   public static string Encrypt(string Text)

                   {

            return Encrypt(Text, "litianping");

                   }

                   /// <summary>

                   /// 加密數據

                   /// </summary>

                   /// <param name="Text"></param>

                   /// <param name="sKey"></param>

                   /// <returns></returns>

                   public static string Encrypt(string Text,string sKey)

                   {

                            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                            byte[] inputByteArray;

                            inputByteArray=Encoding.Default.GetBytes(Text);

                            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));

                            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));

                            System.IO.MemoryStream ms=new System.IO.MemoryStream();

                            CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write);

                            cs.Write(inputByteArray,0,inputByteArray.Length);

                            cs.FlushFinalBlock();

                            StringBuilder ret=new StringBuilder();

                            foreach( byte b in ms.ToArray())

                            {

                                     ret.AppendFormat("{0:X2}",b);

                            }

                            return ret.ToString();

                   }

 

                   #endregion

                  

                   #region ========解密========

  

 

        /// <summary>

        /// 解密

        /// </summary>

        /// <param name="Text"></param>

        /// <returns></returns>

                   public static string Decrypt(string Text)

                   {

            return Decrypt(Text, "litianping");

                   }

                   /// <summary>

                   /// 解密數據

                   /// </summary>

                   /// <param name="Text"></param>

                   /// <param name="sKey"></param>

                   /// <returns></returns>

                   public static string Decrypt(string Text,string sKey)

                   {

                            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                            int len;

                            len=Text.Length/2;

                            byte[] inputByteArray = new byte[len];

                            int x,i;

                            for(x=0;x<len;x++)

                            {

                                     i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);

                                     inputByteArray[x]=(byte)i;

                            }

                            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));

                            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));

                            System.IO.MemoryStream ms=new System.IO.MemoryStream();

                            CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write);

                            cs.Write(inputByteArray,0,inputByteArray.Length);

                            cs.FlushFinalBlock();

                            return Encoding.Default.GetString(ms.ToArray());

                   }

 

                   #endregion

 

 

         }

}

-----------------------

using System;

using System.Collections;

using System.Collections.Specialized;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Data.Common;

using System.Collections.Generic;

namespace Maticsoft.DBUtility

{

    /// <summary>

    /// 數據訪問抽象基礎類

    /// Copyright (C) Maticsoft

    /// </summary>

    public abstract class DbHelperSQL

    {

        //數據庫鏈接字符串(web.config來配置),多數據庫可以使用DbHelperSQLP來實現.

        public static string connectionString = PubConstant.ConnectionString;                    

        public DbHelperSQL()

        {           

        }

 

        #region 公用方法

        /// <summary>

        /// 判斷是否存在某表的某個字段

        /// </summary>

        /// <param name="tableName">表名稱</param>

        /// <param name="columnName">列名稱</param>

        /// <returns>是否存在</returns>

        public static bool ColumnExists(string tableName, string columnName)

        {

            string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'";

            object res = GetSingle(sql);

            if (res == null)

            {

                return false;

            }

            return Convert.ToInt32(res) > 0;

        }

        public static int GetMaxID(string FieldName, string TableName)

        {

            string strsql = "select max(" + FieldName + ")+1 from " + TableName;

            object obj = GetSingle(strsql);

            if (obj == null)

            {

                return 1;

            }

            else

            {

                return int.Parse(obj.ToString());

            }

        }

        public static bool Exists(string strSql)

        {

            object obj = GetSingle(strSql);

            int cmdresult;

            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))

            {

                cmdresult = 0;

            }

            else

            {

                cmdresult = int.Parse(obj.ToString());

            }

            if (cmdresult == 0)

            {

                return false;

            }

            else

            {

                return true;

            }

        }

        /// <summary>

        /// 表是否存在

        /// </summary>

        /// <param name="TableName"></param>

        /// <returns></returns>

        public static bool TabExists(string TableName)

        {

            string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";

            //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";

            object obj = GetSingle(strsql);

            int cmdresult;

            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))

            {

                cmdresult = 0;

            }

            else

            {

                cmdresult = int.Parse(obj.ToString());

            }

            if (cmdresult == 0)

            {

                return false;

            }

            else

            {

                return true;

            }

        }

        public static bool Exists(string strSql, params SqlParameter[] cmdParms)

        {

            object obj = GetSingle(strSql, cmdParms);

            int cmdresult;

            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))

            {

                cmdresult = 0;

            }

            else

            {

                cmdresult = int.Parse(obj.ToString());

            }

            if (cmdresult == 0)

            {

                return false;

            }

            else

            {

                return true;

            }

        }

        #endregion

 

        #region  執行簡單SQL語句

 

        /// <summary>

        /// 執行SQL語句,返回影響的記錄數

        /// </summary>

        /// <param name="SQLString">SQL語句</param>

        /// <returns>影響的記錄數</returns>

        public static int ExecuteSql(string SQLString)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                using (SqlCommand cmd = new SqlCommand(SQLString, connection))

                {

                    try

                    {

                        connection.Open();

                        int rows = cmd.ExecuteNonQuery();

                        return rows;

                    }

                    catch (System.Data.SqlClient.SqlException e)

                    {

                        connection.Close();

                        throw e;

                    }

                }

            }

        }

 

        public static int ExecuteSqlByTime(string SQLString, int Times)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                using (SqlCommand cmd = new SqlCommand(SQLString, connection))

                {

                    try

                    {

                        connection.Open();

                        cmd.CommandTimeout = Times;

                        int rows = cmd.ExecuteNonQuery();

                        return rows;

                    }

                    catch (System.Data.SqlClient.SqlException e)

                    {

                        connection.Close();

                        throw e;

                    }

                }

            }

        }

     

        /// <summary>

        /// 執行Sql和Oracle滴混合事務

        /// </summary>

        /// <param name="list">SQL命令行列表</param>

        /// <param name="oracleCmdSqlList">Oracle命令行列表</param>

        /// <returns>執行結果 0-因爲SQL形成事務失敗 -1 因爲Oracle形成事務失敗 1-總體事務執行成功</returns>

        public static int ExecuteSqlTran(List<CommandInfo> list, List<CommandInfo> oracleCmdSqlList)

        {

            using (SqlConnection conn = new SqlConnection(connectionString))

            {

                conn.Open();

                SqlCommand cmd = new SqlCommand();

                cmd.Connection = conn;

                SqlTransaction tx = conn.BeginTransaction();

                cmd.Transaction = tx;

                try

                {

                    foreach (CommandInfo myDE in list)

                    {

                        string cmdText = myDE.CommandText;

                        SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters;

                        PrepareCommand(cmd, conn, tx, cmdText, cmdParms);

                        if (myDE.EffentNextType == EffentNextType.SolicitationEvent)

                        {

                            if (myDE.CommandText.ToLower().IndexOf("count(") == -1)

                            {

                                tx.Rollback();

                                throw new Exception("違背要求"+myDE.CommandText+"必須符合select count(..的格式");

                                //return 0;

                            }

 

                            object obj = cmd.ExecuteScalar();

                            bool isHave = false;

                            if (obj == null && obj == DBNull.Value)

                            {

                                isHave = false;

                            }

                            isHave = Convert.ToInt32(obj) > 0;

                            if (isHave)

                            {

                                //引起事件

                                myDE.OnSolicitationEvent();

                            }

                        }

                        if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)

                        {

                            if (myDE.CommandText.ToLower().IndexOf("count(") == -1)

                            {

                                tx.Rollback();

                                throw new Exception("SQL:違背要求" + myDE.CommandText + "必須符合select count(..的格式");

                                //return 0;

                            }

 

                            object obj = cmd.ExecuteScalar();

                            bool isHave = false;

                            if (obj == null && obj == DBNull.Value)

                            {

                                isHave = false;

                            }

                            isHave = Convert.ToInt32(obj) > 0;

 

                            if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)

                            {

                                tx.Rollback();

                                throw new Exception("SQL:違背要求" + myDE.CommandText + "返回值必須大於0");

                                //return 0;

                            }

                            if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)

                            {

                                tx.Rollback();

                                throw new Exception("SQL:違背要求" + myDE.CommandText + "返回值必須等於0");

                                //return 0;

                            }

                            continue;

                        }

                        int val = cmd.ExecuteNonQuery();

                        if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)

                        {

                            tx.Rollback();

                            throw new Exception("SQL:違背要求" + myDE.CommandText + "必須有影響行");

                            //return 0;

                        }

                        cmd.Parameters.Clear();

                    }

                    string oraConnectionString = PubConstant.GetConnectionString("ConnectionStringPPC");

                    bool res = OracleHelper.ExecuteSqlTran(oraConnectionString, oracleCmdSqlList);

                    if (!res)

                    {

                        tx.Rollback();

                        throw new Exception("Oracle執行失敗");

                        // return -1;

                    }

                    tx.Commit();

                    return 1;

                }

                catch (System.Data.SqlClient.SqlException e)

                {

                    tx.Rollback();

                    throw e;

                }

                catch (Exception e)

                {

                    tx.Rollback();

                    throw e;

                }

            }

        }       

        /// <summary>

        /// 執行多條SQL語句,實現數據庫事務。

        /// </summary>

        /// <param name="SQLStringList">多條SQL語句</param>                  

        public static int ExecuteSqlTran(List<String> SQLStringList)

        {

            using (SqlConnection conn = new SqlConnection(connectionString))

            {

                conn.Open();

                SqlCommand cmd = new SqlCommand();

                cmd.Connection = conn;

                SqlTransaction tx = conn.BeginTransaction();

                cmd.Transaction = tx;

                try

                {

                    int count = 0;

                    for (int n = 0; n < SQLStringList.Count; n++)

                    {

                        string strsql = SQLStringList[n];

                        if (strsql.Trim().Length > 1)

                        {

                            cmd.CommandText = strsql;

                            count += cmd.ExecuteNonQuery();

                        }

                    }

                    tx.Commit();

                    return count;

                }

                catch

                {

                    tx.Rollback();

                    return 0;

                }

            }

        }

        /// <summary>

        /// 執行帶一個存儲過程參數的的SQL語句。

        /// </summary>

        /// <param name="SQLString">SQL語句</param>

        /// <param name="content">參數內容,好比一個字段是格式複雜的文章,有特殊符號,能夠經過這個方式添加</param>

        /// <returns>影響的記錄數</returns>

        public static int ExecuteSql(string SQLString, string content)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                SqlCommand cmd = new SqlCommand(SQLString, connection);

                System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);

                myParameter.Value = content;

                cmd.Parameters.Add(myParameter);

                try

                {

                    connection.Open();

                    int rows = cmd.ExecuteNonQuery();

                    return rows;

                }

                catch (System.Data.SqlClient.SqlException e)

                {

                    throw e;

                }

                finally

                {

                    cmd.Dispose();

                    connection.Close();

                }

            }

        }

        /// <summary>

        /// 執行帶一個存儲過程參數的的SQL語句。

        /// </summary>

        /// <param name="SQLString">SQL語句</param>

        /// <param name="content">參數內容,好比一個字段是格式複雜的文章,有特殊符號,能夠經過這個方式添加</param>

        /// <returns>影響的記錄數</returns>

        public static object ExecuteSqlGet(string SQLString, string content)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                SqlCommand cmd = new SqlCommand(SQLString, connection);

                System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);

                myParameter.Value = content;

                cmd.Parameters.Add(myParameter);

                try

                {

                    connection.Open();

                    object obj = cmd.ExecuteScalar();

                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))

                    {

                        return null;

                    }

                    else

                    {

                        return obj;

                    }

                }

                catch (System.Data.SqlClient.SqlException e)

                {

                    throw e;

                }

                finally

                {

                    cmd.Dispose();

                    connection.Close();

                }

            }

        }

        /// <summary>

        /// 向數據庫裏插入圖像格式的字段(和上面狀況相似的另外一種實例)

        /// </summary>

        /// <param name="strSQL">SQL語句</param>

        /// <param name="fs">圖像字節,數據庫的字段類型爲image的狀況</param>

        /// <returns>影響的記錄數</returns>

        public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                SqlCommand cmd = new SqlCommand(strSQL, connection);

                System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image);

                myParameter.Value = fs;

                cmd.Parameters.Add(myParameter);

                try

                {

                    connection.Open();

                    int rows = cmd.ExecuteNonQuery();

                    return rows;

                }

                catch (System.Data.SqlClient.SqlException e)

                {

                    throw e;

                }

                finally

                {

                    cmd.Dispose();

                    connection.Close();

                }

            }

        }

 

        /// <summary>

        /// 執行一條計算查詢結果語句,返回查詢結果(object)。

        /// </summary>

        /// <param name="SQLString">計算查詢結果語句</param>

        /// <returns>查詢結果(object)</returns>

        public static object GetSingle(string SQLString)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                using (SqlCommand cmd = new SqlCommand(SQLString, connection))

                {

                    try

                    {

                        connection.Open();

                        object obj = cmd.ExecuteScalar();

                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))

                        {

                            return null;

                        }

                        else

                        {

                            return obj;

                        }

                    }

                    catch (System.Data.SqlClient.SqlException e)

                    {

                        connection.Close();

                        throw e;

                    }

                }

            }

        }

        public static object GetSingle(string SQLString, int Times)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                using (SqlCommand cmd = new SqlCommand(SQLString, connection))

                {

                    try

                    {

                        connection.Open();

                        cmd.CommandTimeout = Times;

                        object obj = cmd.ExecuteScalar();

                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))

                        {

                            return null;

                        }

                        else

                        {

                            return obj;

                        }

                    }

                    catch (System.Data.SqlClient.SqlException e)

                    {

                        connection.Close();

                        throw e;

                    }

                }

            }

        }

        /// <summary>

        /// 執行查詢語句,返回SqlDataReader ( 注意:調用該方法後,必定要對SqlDataReader進行Close )

        /// </summary>

        /// <param name="strSQL">查詢語句</param>

        /// <returns>SqlDataReader</returns>

        public static SqlDataReader ExecuteReader(string strSQL)

        {

            SqlConnection connection = new SqlConnection(connectionString);

            SqlCommand cmd = new SqlCommand(strSQL, connection);

            try

            {

                connection.Open();

                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                return myReader;

            }

            catch (System.Data.SqlClient.SqlException e)

            {

                throw e;

            }  

 

        }

        /// <summary>

        /// 執行查詢語句,返回DataSet

        /// </summary>

        /// <param name="SQLString">查詢語句</param>

        /// <returns>DataSet</returns>

        public static DataSet Query(string SQLString)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                DataSet ds = new DataSet();

                try

                {

                    connection.Open();

                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);

                    command.Fill(ds, "ds");

                }

                catch (System.Data.SqlClient.SqlException ex)

                {

                    throw new Exception(ex.Message);

                }

                return ds;

            }

        }

        public static DataSet Query(string SQLString, int Times)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                DataSet ds = new DataSet();

                try

                {

                    connection.Open();

                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);

                    command.SelectCommand.CommandTimeout = Times;

                    command.Fill(ds, "ds");

                }

                catch (System.Data.SqlClient.SqlException ex)

                {

                    throw new Exception(ex.Message);

                }

                return ds;

            }

        }

 

 

 

        #endregion

 

        #region 執行帶參數的SQL語句

 

        /// <summary>

        /// 執行SQL語句,返回影響的記錄數

        /// </summary>

        /// <param name="SQLString">SQL語句</param>

        /// <returns>影響的記錄數</returns>

        public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                using (SqlCommand cmd = new SqlCommand())

                {

                    try

                    {

                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);

                        int rows = cmd.ExecuteNonQuery();

                        cmd.Parameters.Clear();

                        return rows;

                    }

                    catch (System.Data.SqlClient.SqlException e)

                    {

                        throw e;

                    }

                }

            }

        }

        /// <summary>

        /// 執行多條SQL語句,實現數據庫事務。

        /// </summary>

        /// <param name="SQLStringList">SQL語句的哈希表(key爲sql語句,value是該語句的SqlParameter[])</param>

        public static void ExecuteSqlTran(Hashtable SQLStringList)

        {

            using (SqlConnection conn = new SqlConnection(connectionString))

            {

                conn.Open();

                using (SqlTransaction trans = conn.BeginTransaction())

                {

                    SqlCommand cmd = new SqlCommand();

                    try

                    {

                        //循環

                        foreach (DictionaryEntry myDE in SQLStringList)

                        {

                            string cmdText = myDE.Key.ToString();

                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;

                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);

                            int val = cmd.ExecuteNonQuery();

                            cmd.Parameters.Clear();

                        }

                        trans.Commit();

                    }

                    catch

                    {

                        trans.Rollback();

                        throw;

                    }

                }

            }

        }

        /// <summary>

        /// 執行多條SQL語句,實現數據庫事務。

        /// </summary>

        /// <param name="SQLStringList">SQL語句的哈希表(key爲sql語句,value是該語句的SqlParameter[])</param>

        public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList)

        {

            using (SqlConnection conn = new SqlConnection(connectionString))

            {

                conn.Open();

                using (SqlTransaction trans = conn.BeginTransaction())

                {

                    SqlCommand cmd = new SqlCommand();

                    try

                    { int count = 0;

                        //循環

                        foreach (CommandInfo myDE in cmdList)

                        {

                            string cmdText = myDE.CommandText;

                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters;

                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);

                          

                            if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)

                            {

                                if (myDE.CommandText.ToLower().IndexOf("count(") == -1)

                                {

                                    trans.Rollback();

                                    return 0;

                                }

 

                                object obj = cmd.ExecuteScalar();

                                bool isHave = false;

                                if (obj == null && obj == DBNull.Value)

                                {

                                    isHave = false;

                                }

                                isHave = Convert.ToInt32(obj) > 0;

 

                                if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)

                                {

                                    trans.Rollback();

                                    return 0;

                                }

                                if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)

                                {

                                    trans.Rollback();

                                    return 0;

                                }

                                continue;

                            }

                            int val = cmd.ExecuteNonQuery();

                            count += val;

                            if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)

                            {

                                trans.Rollback();

                                return 0;

                            }

                            cmd.Parameters.Clear();

                        }

                        trans.Commit();

                        return count;

                    }

                    catch

                    {

                        trans.Rollback();

                        throw;

                    }

                }

            }

        }

        /// <summary>

        /// 執行多條SQL語句,實現數據庫事務。

        /// </summary>

        /// <param name="SQLStringList">SQL語句的哈希表(key爲sql語句,value是該語句的SqlParameter[])</param>

        public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList)

        {

            using (SqlConnection conn = new SqlConnection(connectionString))

            {

                conn.Open();

                using (SqlTransaction trans = conn.BeginTransaction())

                {

                    SqlCommand cmd = new SqlCommand();

                    try

                    {

                        int indentity = 0;

                        //循環

                        foreach (CommandInfo myDE in SQLStringList)

                        {

                            string cmdText = myDE.CommandText;

                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters;

                            foreach (SqlParameter q in cmdParms)

                            {

                                if (q.Direction == ParameterDirection.InputOutput)

                                {

                                    q.Value = indentity;

                                }

                            }

                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);

                            int val = cmd.ExecuteNonQuery();

                            foreach (SqlParameter q in cmdParms)

                            {

                                if (q.Direction == ParameterDirection.Output)

                                {

                                    indentity = Convert.ToInt32(q.Value);

                                }

                            }

                            cmd.Parameters.Clear();

                        }

                        trans.Commit();

                    }

                    catch

                    {

                        trans.Rollback();

                        throw;

                    }

                }

            }

        }

        /// <summary>

        /// 執行多條SQL語句,實現數據庫事務。

        /// </summary>

        /// <param name="SQLStringList">SQL語句的哈希表(key爲sql語句,value是該語句的SqlParameter[])</param>

        public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)

        {

            using (SqlConnection conn = new SqlConnection(connectionString))

            {

                conn.Open();

                using (SqlTransaction trans = conn.BeginTransaction())

                {

                    SqlCommand cmd = new SqlCommand();

                    try

                    {

                        int indentity = 0;

                        //循環

                        foreach (DictionaryEntry myDE in SQLStringList)

                        {

                            string cmdText = myDE.Key.ToString();

                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;

                            foreach (SqlParameter q in cmdParms)

                            {

                                if (q.Direction == ParameterDirection.InputOutput)

                                {

                                    q.Value = indentity;

                                }

                            }

                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);

                            int val = cmd.ExecuteNonQuery();

                            foreach (SqlParameter q in cmdParms)

                            {

                                if (q.Direction == ParameterDirection.Output)

                                {

                                    indentity = Convert.ToInt32(q.Value);

                                }

                            }

                            cmd.Parameters.Clear();

                        }

                        trans.Commit();

                    }

                    catch

                    {

                        trans.Rollback();

                        throw;

                    }

                }

            }

        }

        /// <summary>

        /// 執行一條計算查詢結果語句,返回查詢結果(object)。

        /// </summary>

        /// <param name="SQLString">計算查詢結果語句</param>

        /// <returns>查詢結果(object)</returns>

        public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                using (SqlCommand cmd = new SqlCommand())

                {

                    try

                    {

                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);

                        object obj = cmd.ExecuteScalar();

                        cmd.Parameters.Clear();

                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))

                        {

                            return null;

                        }

                        else

                        {

                            return obj;

                        }

                    }

                    catch (System.Data.SqlClient.SqlException e)

                    {

                        throw e;

                    }

                }

            }

        }

 

        /// <summary>

        /// 執行查詢語句,返回SqlDataReader ( 注意:調用該方法後,必定要對SqlDataReader進行Close )

        /// </summary>

        /// <param name="strSQL">查詢語句</param>

        /// <returns>SqlDataReader</returns>

        public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)

        {

            SqlConnection connection = new SqlConnection(connectionString);

            SqlCommand cmd = new SqlCommand();

            try

            {

                PrepareCommand(cmd, connection, null, SQLString, cmdParms);

                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                cmd.Parameters.Clear();

                return myReader;

            }

            catch (System.Data.SqlClient.SqlException e)

            {

                throw e;

            }

            //                         finally

            //                         {

            //                                  cmd.Dispose();

            //                                  connection.Close();

            //                         }       

 

        }

 

        /// <summary>

        /// 執行查詢語句,返回DataSet

        /// </summary>

        /// <param name="SQLString">查詢語句</param>

        /// <returns>DataSet</returns>

        public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                SqlCommand cmd = new SqlCommand();

                PrepareCommand(cmd, connection, null, SQLString, cmdParms);

                using (SqlDataAdapter da = new SqlDataAdapter(cmd))

                {

                    DataSet ds = new DataSet();

                    try

                    {

                        da.Fill(ds, "ds");

                        cmd.Parameters.Clear();

                    }

                    catch (System.Data.SqlClient.SqlException ex)

                    {

                        throw new Exception(ex.Message);

                    }

                    return ds;

                }

            }

        }

 

 

        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)

        {

            if (conn.State != ConnectionState.Open)

                conn.Open();

            cmd.Connection = conn;

            cmd.CommandText = cmdText;

            if (trans != null)

                cmd.Transaction = trans;

            cmd.CommandType = CommandType.Text;//cmdType;

            if (cmdParms != null)

            {

 

 

                foreach (SqlParameter parameter in cmdParms)

                {

                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&

                        (parameter.Value == null))

                    {

                        parameter.Value = DBNull.Value;

                    }

                    cmd.Parameters.Add(parameter);

                }

            }

        }

 

        #endregion

 

        #region 存儲過程操做

 

        /// <summary>

        /// 執行存儲過程,返回SqlDataReader ( 注意:調用該方法後,必定要對SqlDataReader進行Close )

        /// </summary>

        /// <param name="storedProcName">存儲過程名</param>

        /// <param name="parameters">存儲過程參數</param>

        /// <returns>SqlDataReader</returns>

        public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)

        {

            SqlConnection connection = new SqlConnection(connectionString);

            SqlDataReader returnReader;

            connection.Open();

            SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);

            command.CommandType = CommandType.StoredProcedure;

            returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);

            return returnReader;

           

        }

 

 

        /// <summary>

        /// 執行存儲過程

        /// </summary>

        /// <param name="storedProcName">存儲過程名</param>

        /// <param name="parameters">存儲過程參數</param>

        /// <param name="tableName">DataSet結果中的表名</param>

        /// <returns>DataSet</returns>

        public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                DataSet dataSet = new DataSet();

                connection.Open();

                SqlDataAdapter sqlDA = new SqlDataAdapter();

                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);

                sqlDA.Fill(dataSet, tableName);

                connection.Close();

                return dataSet;

            }

        }

        public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                DataSet dataSet = new DataSet();

                connection.Open();

                SqlDataAdapter sqlDA = new SqlDataAdapter();

                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);

                sqlDA.SelectCommand.CommandTimeout = Times;

                sqlDA.Fill(dataSet, tableName);

                connection.Close();

                return dataSet;

            }

        }

 

 

        /// <summary>

        /// 構建 SqlCommand 對象(用來返回一個結果集,而不是一個整數值)

        /// </summary>

        /// <param name="connection">數據庫鏈接</param>

        /// <param name="storedProcName">存儲過程名</param>

        /// <param name="parameters">存儲過程參數</param>

        /// <returns>SqlCommand</returns>

        private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)

        {

            SqlCommand command = new SqlCommand(storedProcName, connection);

            command.CommandType = CommandType.StoredProcedure;

            foreach (SqlParameter parameter in parameters)

            {

                if (parameter != null)

                {

                    // 檢查未分配值的輸出參數,將其分配以DBNull.Value.

                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&

                        (parameter.Value == null))

                    {

                        parameter.Value = DBNull.Value;

                    }

                    command.Parameters.Add(parameter);

                }

            }

 

            return command;

        }

 

        /// <summary>

        /// 執行存儲過程,返回影響的行數          

        /// </summary>

        /// <param name="storedProcName">存儲過程名</param>

        /// <param name="parameters">存儲過程參數</param>

        /// <param name="rowsAffected">影響的行數</param>

        /// <returns></returns>

        public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)

        {

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                int result;

                connection.Open();

                SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);

                rowsAffected = command.ExecuteNonQuery();

                result = (int)command.Parameters["ReturnValue"].Value;

                //Connection.Close();

                return result;

            }

        }

 

        /// <summary>

        /// 建立 SqlCommand 對象實例(用來返回一個整數值)  

        /// </summary>

        /// <param name="storedProcName">存儲過程名</param>

        /// <param name="parameters">存儲過程參數</param>

        /// <returns>SqlCommand 對象實例</returns>

        private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)

        {

            SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);

            command.Parameters.Add(new SqlParameter("ReturnValue",

                SqlDbType.Int, 4, ParameterDirection.ReturnValue,

                false, 0, 0, string.Empty, DataRowVersion.Default, null));

            return command;

        }

        #endregion

 

    }

 

}

-----------------邊框;

   <fieldset class="changePassword">

                    <legend>賬戶信息</legend>

----------------------------------------------------動軟的緩存類

using System;

using System.Web;

 

namespace Maticsoft.Common

{

         /// <summary>

         /// 緩存相關的操做類

    /// Copyright (C) Maticsoft

         /// </summary>

         public class DataCache

         {

                   /// <summary>

                   /// 獲取當前應用程序指定CacheKey的Cache值

                   /// </summary>

                   /// <param name="CacheKey"></param>

                   /// <returns></returns>

        public static object GetCache(string CacheKey)

        {

            System.Web.Caching.Cache objCache = HttpRuntime.Cache;

            return objCache[CacheKey];

        }

                   /// <summary>

                   /// 設置當前應用程序指定CacheKey的Cache值

                   /// </summary>

                   /// <param name="CacheKey"></param>

                   /// <param name="objObject"></param>

                   public static void SetCache(string CacheKey, object objObject)

                   {

                            System.Web.Caching.Cache objCache = HttpRuntime.Cache;

                            objCache.Insert(CacheKey, objObject);

                   }

 

                   /// <summary>

                   /// 設置當前應用程序指定CacheKey的Cache值

                   /// </summary>

                   /// <param name="CacheKey"></param>

                   /// <param name="objObject"></param>

                   public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration,TimeSpan slidingExpiration )

                   {

                            System.Web.Caching.Cache objCache = HttpRuntime.Cache;

                            objCache.Insert(CacheKey, objObject,null,absoluteExpiration,slidingExpiration);

                   }

         }

}

-----------------------------------刪除最後一個逗號

 return str.Substring(0, str.LastIndexOf(","));

-----------------------生成查詢條件案例

   /// <summary>

        /// 生成查詢條件

        /// </summary>

        /// <param name="model"></param>

        /// <param name="paramters"></param>

        /// <returns></returns>

        public static string CreateSqlStr(WorkersModel model,List<SqlParameter> paramters)

        {

            StringBuilder sql = new StringBuilder();

            if (model != null)

            {

                if (!string.IsNullOrEmpty(model.Name))

                {

                    sql.Append(" and Name like @Name");

                    paramters.Add(new SqlParameter("@Name","%"+model.Name+"%"));

                }

                if (!string.IsNullOrEmpty(model.IdCard))

                {

                    sql.Append(" and IdCard like @IdCard");

                    paramters.Add(new SqlParameter("@IdCard", "%" + model.IdCard + "%"));

                }

            }

            return sql.ToString();

        }

    }

--------------------------enabled=fase;不會保存視圖狀態;

 document.getElementById("txtName").disabled=true;這種也不會保存視圖狀態,只能手動保存了,記住奧;

固然也能夠用js控制hildfiled部分;

--------------------------------------彈出提示框進行選擇!!!

  function ChooseDele()

    {

       if(confirm("是否同時刪除供應商複覈與供應商複評與供應商調查裏的數據?"))

          {

            document.getElementById("hidCommon").value="allDel";

            document.getElementById("hidXtBH").value=bh;

           

          }else

          {

            document.getElementById("hidCommon").value="Only";

            document.getElementById("hidXtBH").value=bh;

          }

//          __doPostBack("UpdatePanel1","");

         document.form1.submit();

    }

-----------------------------------------數據庫中判斷字段是否爲空

IF @d is null

-----------------------------------------------------引覺得豪的sql拼接:最複雜的sql拼接:經典之做

  public static DataTable GetStatistics(WorkRecordsModel model)

       {

           //因爲無必要新創實體,返回datatable類型

           List<SqlParameter> list = new List<SqlParameter>();

           StringBuilder strSql = new StringBuilder();

           strSql.Append("SELECT Workers.[Name],Workers.IdCard,sum(WR.WorkDays)as sumdays,sum(WR.Wages)as sumwages,");

           strSql.Append("sum(PW1.AllWages)as sumallwages0,sum(PW2.AllWages) as sumallwages1 FROM Workers where 1=1");

           if (model.Name != "" || model.Name != null)

           {

               strSql.Append(" and Name like @Name");

               list.Add(new SqlParameter("@Name", "%" + model.Name + "%"));

           }

           strSql.Append("  LEFT join (select * from WorkRecords where [Date]>=@begindate and [Date]<=@enddate");

           if (model.XMId != null || model.XMId != 0)

           {

               strSql.Append("  and XMId=@XMId");

               list.Add(new SqlParameter("@XMId",model.XMId));

           }

           strSql.Append("  )as WR on Workers.IdCard=WR.IdCard");

           strSql.Append("  LEFT JOIN  (SELECT * FROM PayWages WHERE [Date]>=@begindate and [Date]<=@enddate AND Type=0) as PW1 ON Workers.IdCard=PW1.IdCard");

           strSql.Append("  LEFT JOIN  (SELECT * FROM PayWages WHERE [Date]>=@begindate and [Date]<=@enddate AND Type=1) as PW2 ON Workers.IdCard=PW2.IdCard");

           strSql.Append(" GROUP BY Workers.[Name],Workers.IdCard");

           list.Add(new SqlParameter("@begindate",model.BeginTime));

           list.Add(new SqlParameter("@enddate",model.EndTime));

           DataTable table=new DataTable();//ui只需判斷rows.count即可

           table= DBHelperXT.GetDataSet(strSql.ToString(),list.ToArray());

           return table;

       }

------------------------獲取本月第一天,本週第一天;

namespace MyOffice.Framework

{

    public class DateProvider

    {

        /// <summary>

        /// 本週的第一天

        /// </summary>

        /// <returns></returns>

        public static DateTime CurrentWeekStartDay()

        {

            int spanDays=0;

            switch (DateTime.Now.DayOfWeek)

            {

                case DayOfWeek.Monday: spanDays = 0;

 

                    break;

 

                case DayOfWeek.Tuesday: spanDays = 1;

 

                    break;

 

                case DayOfWeek.Wednesday: spanDays = 2;

 

                    break;

 

                case DayOfWeek.Thursday: spanDays = 3;

 

                    break;

 

                case DayOfWeek.Friday: spanDays = 4;

 

                    break;

 

                case DayOfWeek.Saturday: spanDays = 5;

 

                    break;

 

                case DayOfWeek.Sunday: spanDays = 6;

 

                    break;

 

            }

            DateTime start = DateTime.Today.AddDays(-spanDays);

            return start;

        }

    /// <summary>

    /// 本月的第一天

    /// </summary>

    /// <returns></returns>

        public static DateTime CurrentMonthStartDay()

        {

            DateTime start = DateTime.Today.AddDays(-DateTime.Today.Day + 1);

            return start;

        }

         

    }

}

-------------------------經典sql拼接;

  //因爲無必要新創實體,返回datatable類型

           List<SqlParameter> list = new List<SqlParameter>();

           StringBuilder strSql = new StringBuilder();

           page.TotalRow = GetStatisticsCount(model);

           strSql.Append("select * from (SELECT Workers.[Name],Workers.IdCard,WR.sumdays,WR.sumwages,");

           strSql.Append(" PW1.sumallwages0,PW2.sumallwages1,row_number() over(order by Workers.Name) as rowId FROM Workers");

           strSql.Append(" LEFT join (select WR1.IdCard,sum(WR1.WorkDays) as sumdays,sum(WR1.Wages) as sumwages");

           strSql.Append(" from (select * from WorkRecords where [Date]>=@begindate and [Date]<=@enddate");

           if (model.XMId != 0)

           {

               strSql.Append(" and XMId=@XMId");

               list.Add(new SqlParameter("@XMId", model.XMId));

           }

           strSql.Append(" ) as WR1 group by WR1.IdCard");

           strSql.Append(" )as WR on Workers.IdCard=WR.IdCard");

           strSql.Append(" LEFT JOIN  (SELECT PW11.IdCard,sum(PW11.AllWages) as sumallwages0 FROM");

           strSql.Append(" (select * from PayWages WHERE [Date]>=@begindate and [Date]<=@enddate AND Type=0) as PW11");

           strSql.Append(" group by PW11.IdCard) as PW1 ON Workers.IdCard=PW1.IdCard");

           strSql.Append(" LEFT JOIN  (SELECT PW22.IdCard,sum(PW22.AllWages) as sumallwages1 FROM");

           strSql.Append(" (select * from PayWages WHERE [Date]>=@begindate and [Date]<=@enddate AND Type=1) as PW22 ");

           strSql.Append(" group by PW22.IdCard) as PW2 ON Workers.IdCard=PW2.IdCard");

           if (model.Name != "" || model.Name != null)

           {

               strSql.Append("  where Workers.[Name] like @name");

               list.Add(new SqlParameter("@Name", "%" + model.Name + "%"));

           }

           strSql.Append(" ) as T where T.rowId between ").Append(page.Begin).Append(" and ").Append(page.End);

           list.Add(new SqlParameter("@begindate", model.BeginTime));

           list.Add(new SqlParameter("@enddate", model.EndTime));

           DataTable table = new DataTable();//ui只需判斷rows.count即可

           table = DBHelperXT.GetDataSet(strSql.ToString(), list.ToArray());

------------------------------------

            txtBeginTime.Text = DateTime.Today.AddDays(-DateTime.Today.Day + 1).ToString("yyyy-MM-dd");

            txtEndTime.Text = DateTime.Now.ToString("yyyy-MM-dd");

-----------------------------------------------------------------------cube grouping rollup的使用;

SELECT CASE WHEN grouping(Name)=1 THEN '合計' ELSE Name END as 姓名,

CASE WHEN grouping(Sex)=1 THEN '合計' ELSE sex END as 性別

,sum(Score) as 總成績

from Score

GROUP BY name,Sex WITH CUBE

--當出現with rollup 根據by後面第一個字段分組進行彙總,聚合性別;

--若group by sex,Name WITH rollup則根據性別分組,聚合姓名;(男的有多少,女的有多少)

---若with cube,則以group by 後面的多列進行分組,多個維度分組;by後的第一個字段;(順序爲:根據性別聚合,總聚合,根據名稱聚合)

------------count(1)和count(*)是等效的,都會返回本列的行數;

-------------------------------------------------------------------統計報表(合計、小計:cube rollup grouping的用法)

create table #t(a int,b int,c int,d int,e int)

insert into #t values(1,2,3,4,5)

insert into #t values(1,2,3,4,6)

insert into #t values(1,2,3,4,7)

insert into #t values(1,2,3,4,8)

insert into #t values(1,3,3,4,5)

insert into #t values(1,3,3,4,6)

insert into #t values(1,3,3,4,8)

insert into #t values(1,3,3,4,7)

 

insert into #t values(2,2,2,4,5)

insert into #t values(2,2,3,4,6)

insert into #t values(2,2,4,4,7)

insert into #t values(2,2,5,4,8)

insert into #t values(2,3,6,4,5)

insert into #t values(2,3,3,4,6)

insert into #t values(2,3,3,4,8)

insert into #t values(2,3,3,4,7)

狀況一:只有一個分類彙總列時,只須要一個合計。只須要增長with rollup便可。(一個維度的)

select case when grouping(a)=1 then '合計' else cast(a as varchar) end a,

sum(b),sum(c),sum(d),sum(e) from #t group by a with rollup

狀況二:有多個分類彙總列,只須要一個合計.增長rollup以後,須要增長判斷。

select case when grouping(a)=1 then '合計' else cast(a as varchar) end a,

    b,

sum(c),sum(d),sum(e) from #t

group by a,b with rollup

having grouping(b)=0 or grouping(a)=1

 

select case when grouping(a)=1 then '合計' else cast(a as varchar) end a,

    b,

    c,

sum(d),sum(e) from #t

group by a,b,c with rollup

having grouping(c)=0 or grouping(a)=1

狀況三:有多個分類彙總列,須要所有的小計和合計

select case when grouping(a)=1 then '合計' else cast(a as varchar) end a,

    case when grouping(b)=1 and grouping(a)=0 then '小計' else cast(b as varchar) end b,

    case when grouping(c)=1 and grouping(b)=0 then '小計' else cast(c as varchar) end c,

sum(d),sum(e) from #t

group by a,b,c with rollup

另一種顯示小計的方式

select case when grouping(a)=1 then '合計'

    when grouping(b)=1 then cast(a as varchar)+'小計'

    else cast(a as varchar) end a,

    case when grouping(b)=0 and grouping(c)=1

    then cast(b as varchar)+'小計' else cast(b as varchar) end b,

    case when grouping(c)=1 and grouping(b)=0

    then '' else cast(c as varchar) end c,

sum(d),sum(e) from #t

group by a,b,c with rollup

狀況四:有多個分類彙總列,須要部分的小計和合計

select case when grouping(a)=1 then '合計' else cast(a as varchar) end a,

    b,

    case when grouping(c)=1 and grouping(b)=0 then '小計' else cast(c as varchar) end c,

sum(d),sum(e) from #t

group by a,b,c with rollup

having grouping(a)=1 or grouping(b)=0

---

select case when grouping(a)=1 then '合計' else cast(a as varchar) end a,

    case when grouping(b)=1 and grouping(a)=0 then '小計' else cast(b as varchar) end b,

    c,

sum(d),sum(e) from #t

group by a,b,c with rollup

having grouping(a)=1 or grouping(b)=1 or grouping(c)=0

--

select case when grouping(a)=1 then '合計' else cast(a as varchar) end a,

    b,

    case when grouping(c)=1 and grouping(b)=0 then '小計' else cast(c as varchar) end c,

sum(d),sum(e) from #t

group by a,b,c with rollup

having grouping(a)=1 or grouping(b)=0

--------------------------------------------遞歸遍歷節點案例

  /// <summary>

        /// //根據施工部id遍歷全部子節點id

        /// </summary>

        /// <param name="sgbId"></param>

        /// <returns></returns>

        public static string GetSgbIds(string sgbId)

        {

            StringBuilder strB = new StringBuilder();

            StringBuilder sb = new StringBuilder();

            sb.Append("select BH from ShiGongBuWei where SJ=@SJ");

            SqlParameter[] paras ={

               new SqlParameter("@SJ",sgbId)

            };

            DataTable ta = DBHelper.GetDataSet(sb.ToString(),paras);

            strB.Append(sgbId).Append(",");

            if (ta.Rows.Count != 0)

            {

                foreach (DataRow row in ta.Rows)

                {

                  strB.Append(GetSgbIds(row["BH"].ToString()));

                }

            }

            return strB.ToString();

        }

---------------------------------------------對於存儲過程當中in(@str),這樣是很差用的解決方案有兩個

1.經語句賦值個字符串,再exec();:::in ('+@sgbids+')

2.利用逗號分割函數進行

--------------------------padding能夠擴展元素的空間,好比《a> href>背景範圍比較小,因此須要擴展一下;這樣背景就變大了;

----------------頁面佈局時候:

行級元素經過padding來擴展空間:

塊級元素經過 line-height:100px; padding:8px 12px;二者來擴充空間,由於塊狀不能自動調節行高,二行級能夠。

----------------------------------16乘16小圖標顯示

8)收藏夾小圖標 例如:首先製做一個16x16的icon圖標,命名爲favicon.ico,放在根目錄下。而後將下面的代碼嵌入head區:

<link rel="icon" href="/favicon.ico" type="image/x-icon" />

<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

---------------------------搜索引擎設置(至於title下面)

爲搜索引擎準備的內容

代碼以下,替換成你本身站點的內容就能夠:

? 容許搜索機器人搜索站內全部連接。若是你想某些頁面不被搜索,推薦採用robots.txt方法

<meta content="all" name="robots" />

? 設置站點做者信息

<meta name="author" content="ajie@netease.com,阿捷" />

? 設置站點版權信息

<meta name="Copyright" content="www.w3cn.org,自由版權,任意轉載" />

? 站點的簡要介紹(推薦)

<meta name="description" content="新網頁設計師。web標準的教程站點,推進web標準在中國的應用" />

? 站點的關鍵詞(推薦)

<meta content="designing, with, web, standards

, xhtml, css, graphic, design, layout, usability, cces

sibility, w3c, w3, w3cn, ajie" name="keywords" /> 先介

紹這麼多。補充說明,前面花了5節都是講head區的代碼,實際頁面

內容還一字未提,呵呵,不要急,其實head區是很是重要的,看一個頁面

的head的代碼就能夠知道設計師是否夠專業。

-------------------------------------------------js獲取身份證號年齡(根據身份證獲取年齡)

 if(idCard.length==15)

    {

        year="19" + idCard.substring(6,8);

        document.getElementById("txtAge").value=dates.getFullYear()-parseInt(year);

    }

    else if(idCard.length==18)

    {

         year=idCard.substring(6,10);

         document.getElementById("txtAge").value=dates.getFullYear()-parseInt(year);

    }

-----------------------------------------------------

9:sql中全部的索引都從1開始;charindex,substring()等;

SET @a=charindex('o',@a)o在@a的位置從1開始;

SET @a=substring(@a,2,2)2:起始,2:長度;

js中s.substring();開始和結束索引

js中s.substr();索引+長度;

------------------------------------------------------------------正則表達式:

//郭澤峯總結:||備註:當 regu是字符串時應示例對象RegExp,不然的話 var emailReg =/在此加上正則/

//驗證郵箱

 function CheckEmail(strEmail) {

            var emailReg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;

            if (emailReg.test(strEmail)) {

                return true;

            }

            else {

                return false;

            }

        };

//驗證是否是數字

 function IsNum(str) {

            //前提是str不爲空!

            //能夠是小數

            if (isNaN(str)) {

                return false;

            }

            else {

                return true;

            }

         };

//驗證是否是整數格式

function IsInteger(str) {

            var regu = /^[-]{0,1}[0-9]{1,}$/;

            return regu.test(str);

        };

 

//驗證是否是爲空(包括空或者是空格!)

 function IsNull(str) {

            if (str == "") {

                return true;

            }

            var regu = "^[ ]+$";

            var re = new RegExp(regu);

            return re.test(str);

        };

//檢查輸入字符串是否只由英文字母和數字和下劃線組成 

 function IsNumberOr_Letter(s) {

            //判斷是不是數字或字母 

            var regu = "^[0-9a-zA-Z\_]+$";

            var re = new RegExp(regu);

            if (re.test(s)) {

                return true;

            }

            else {

                return false;

            }

        };

//判斷是不是漢字、字母、數字或下劃線組成 

function IsChinaOrNumbOrLett(s) {

             //沒必要驗證爲空

            var regu = "^[0-9a-zA-Z\u4e00-\u9fa5\_]+$";

            var re = new RegExp(regu);

            if (re.test(s)) {

                return true;

            }

            else {

                return false;

            }

        };

//去除字符串空格

function Trim(str){ //刪除左右兩端的空格   

return str.replace(/(^\s*)|(\s*$)/g, "");   

}   

function Ltrim(str){ //刪除左邊的空格   

return str.replace(/(^\s*)/g,"");   

}   

function Rtrim(str){ //刪除右邊的空格   

return str.replace(/(\s*$)/g,"");   

}   

//驗證身份證號

 function IsIdCard(str) {

            var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;

            return reg.test(str);

        }

//驗證日期(全部格式均可以)

  function IsDateWithAllForm(str) {

            var reg =/^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:([0-5][0-9])\s))([AM|PM|am|pm]{2,2})))?$/;

            return reg.test(str);

        }

//驗證日期+格式:格式必須爲:2012-12-12這種的; 

function IsDateWithOneForm(str) {

            var reg = /^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$/;

            return reg.test(str);

        }

//驗證位數:/^\d{3}$/:必須爲三位,/^\d{3,6}$/:爲3-6位

 function IsRight(str) {

            var reg = /^\d{3,6}$/;

            return reg.test(str);

        }

//------------------------------------------雜記

數據庫的完整性=可靠性+準確性。

SELECT NEWID()(html中newid()),至關於new guid(),其類型爲uniqueidentifier

數據庫中雙精度用real,單精度:float

-----黑客常常攻破IIS去爲一些html頁面加上iframe;

<iframe src="page1.aspx" style=" display:none"></iframe>

隱藏了可是有;

-----------

var father = window.parent;若三層窗口:var father = window.parent.parent;若:var father = window.Top;top指的是最頂層;

document.getElementById("result").innerHTML = str;//在頁面顯示文字。

-----------

if(typeof(father.accept)=="function")//判斷是否是自定義函數類型

------new Date()獲取新的日期;

 --------------<%=DateTime.Now.ToLocalTime() %>

--------------get參數傳遞方式會在ie頁面進行緩存,可是post不會。

----javascript是區分大小寫的;

===========================================================================================================

ajax中503mistakes 指的是服務未提供,404錯誤指的是未找到;12007錯誤:跨域名錯誤提示

if(x.readyState==4&&x.status==200){}

else{alert(x.status)}//提示錯誤;

-------------///<reference name="MicrosoftAjax.js"/>

 

 

javascript腳本

///<reference name="MicrosoftAjax.js"/>

/// <reference path="JScript2.js" />

/// <reference path="jquery-1.4.1-vsdoc.js" />

 

window.onload= function () {

   

    var s =String.format("hellow:{0}", "abc");

    alert(s);

    var i = addint(1,2);

    alert(i);

     $("#a").html(s); //應用jquery作法

    $get("a").value = s;//這兩行至關於document.getelementbyid();查找元素;

----------------------

 

}

--------------scriptmanage一個頁面只能應用一次;若調用web服務應該命名爲scriptmamageProxy(代理)

--------------ajaxcontroltookit官方下載網址:ajax.aspx.net;

----updatepanel筆記:

有個屬性:updatemode,若選擇conditional則被人不會影響我,不然(aways)全部panel回發;

2)若一個界面有兩個panel則一個(不會發)控制另外一個則設置childrenAStriggers爲false;同時設updatemodles屬性爲conditionals(若爲aways則矛盾)

3)fileupload不支持異步操做

-------------javascript

1)eval函數:用於計算字符串表達式的值;如3+3,var a=eval("3+4")->a=7;

2)isnan函數:用於驗證參數是否爲nan;

3)indexOf("a",0):查找字符串中存在a的位置,不存在返回-1;

4)toLowerCase();轉化小寫;

5)toUpperCase();轉化成大寫;

6)round(y)四捨五入取整;

7)sqrt(y)返回y的平方根;

8)     var da = new Date();

          //        da.setFullYear(2014,1,14);//自定義日期

          //        da.setHours(13,25,32,900);

8)定時:settimeout:一次;setinterval;每隔幾秒一次

9)javascript:var a=[1,2,3,4,5];聲明一個數組(array)

------------------------------選擇器:

1):$("#id")

2):$("元素標籤")

3)$(".css")//內填寫.+樣式名

//迭代:$("#id")返回的是一個數組(自動遍歷);var a=$("#id");if(a.length<=0)alert("沒有此元素")

$(function () {

        $("p").click(function () { $.each($(this).nextAll("p"), function () { $(this).css("background-color", "red"); } )});

    })//階級選擇器

-------------------------------彩色照片變黑白照片:

 <style type="text/css">

        .b

        {  filter:Gray;    

                 }

    </style>

function guo() {

//            $(document.body).toggleClass("b");

//        }

----------------------------------:圖片註冊事件

<img src="img/010610201722.jpg" style="height: 204px; width: 189px" onmouseover="this.src='img/zf-走方格遊戲軟件.PNG'" onmouseout="this.src='img/010610201722.jpg'"/>

 

 

 

----------------------------上級目錄嗲下級目錄則~/;下級目錄調用上級目錄則:../;

 

---------------------------href="read.aspx?id={blogid}#coment實現自動定位:在第二個頁面中加上《a name="coment"></a>

--------------再用repeater時,應刪除selectitem塊中的type="object"才能按id顯示數據。

------------------javas獲取卻string【「id」】-- var blogid = '<%=Request["id"] %>';

 

------------------ $("#ab").toggle("slow");使div其實就開始隱藏

 

--------------------------

<%if (this.xianshi)//xianshi 是在後臺中的屬性

          { %>

        <span class="permalink"><a href='<%# "~/Edite.aspx?blogid="+Eval("blogid") %>' runat="server">編輯</a>

        <a href="#">刪除</a></span>

        <%} %>

}

-------------------new Guid(blogid):blogid 是guid的string("string")形式的,要想轉化爲新的guid 類型則new guid(blogdi)

----------------- <a href="#" df="<%# Eval("blogid") %>" onclick="shan(this.df)">刪除</a></span>

 

------- window.location.reload();卸載jiavascript腳本中,從新加載(刷新)

------window.location.href="default.aspx",從新加載到另外一界面

 

--------------------$(".[tag='delete']").hide() ;取屬性

----------------window.location.href("Default.aspx?uid='"+result.d+"'");

 

-----------------綁定日期

<%# Eval("Datetime","{0:d}")%>

Text='<%# Bind("OnDutyTime1","{0:hh:mm}") %>' />綁定時間部分12

Text='<%# Bind("OnDutyTime1","{0:H:mm}") %>' />24制

-----------------

a.[Order]當order爲關鍵字,因此爲此,不爲[a.order]

一個表能夠有多個列做爲主鍵,擔有且只有一個;

 

----------------

byte[]   by=你讀出來的的圖片的字節

Response.ContentType   =   "image/bmp ";

Response.BinaryWrite(by);

----------------------

protected,類外不能調用,可是繼承類能夠;

-----------------------------------------------------數據庫

isex char(4) check(isex='男' or isex='女'),

 date datetime default '2011-6-6'

----------

drop trigger tr_sd

create trigger tr_sd

on score

after  insert

as

  select * from inserted

  print '你插入了'

---------------

--(7)查詢班級某科科目平均分數

select avg(math) as avg_sco from score

-----------------------

select * from (SELECT Id,Name,Price  from Wuzi) as dd

------------------------

select t1.productid,t1.unitprice

from [order details] as t1 join [order details]

on t1.productid=t2.productid

group by ti.productid,t1.unitprice

having t1.unitprice<avg(t2.unitprice)

------------------------

--可將學生表中的數據導入老師表中

insert teacher

select id,name from student

--------------五種約束;

1.主鍵約束、外鍵約束、檢查約束、默認約束、惟一約束

-sql是structured Query Language 結構化查詢語句

---------T-Sql與sql

t_sql是sql的增強版

對功能進行了補充:變量說明、流程控制、功能函數

-----------

like 'c_'必須是2個字符

單引號表示字符串,與c#不一樣;

like 'c_%'至少兩個,多了不限

lide 'as[1-3]'1-3的數字'%[1-4]'    [1,2,3,4]任選

--------like可放在check中約束:通配符:%、—【】

----------------邏輯表達式:not 1=0;not(a='a')===<>

select 3%2  結果是1;

一張表只能有一個自增列

-------insert into biao(1,2)values(default,'12');

默認插入defalut,或不插

----------union合併數據

select 1 union select 2

-------------truncate table a 全都刪除:自增重置爲1;

delete from table a:一條一條刪

-----------

select aa+'.'+bb from stu;aa bb是列名

-------------

123 as b getdate() as c均可以;

 

address is null ;放於where後面

條件不是空值:

where (not(address is null))

 

 

------select top 20 percent name from student;

 

 

語句能夠出現表達式:如:(aa*30)as b或where (a*23)>30

------------------------------------

SELECT  CASE WHEN number<5 THEN 'z' ELSE 'x' END as 'lllll'

from xin

---------------------------------union的用法,並在下面下面結果只有一列而且必須保證類型一致1,2必須是字符類型

USE xinwen

SELECT  CASE WHEN number<5 THEN '1' ELSE '2' END as 'lllll'

from xin

UNION

SELECT title as cc from xin

--------------------order by後面能夠跟表達式子

as 後面的名稱不能出如今where後,但能夠出如今order by後面

------------------字符串:

SELECT charindex('a','sda',1);返回3,第二個字符串從1開始,和c#不同

select len('123')返回3;

select ltrim('                 123')//消除左側空格。rtrim消除右側空格

select left('1234',2)//取左側兩位

select right('1234',2)

select replace('abcdef','ab','00')

------------結果是00cdef

--------------------

select stuff('abcde',2,3,'11111'):從第2個字符截取3個再塞入最後的字符:a1111e

------------

select dateadd(yy,4,getdate())//加年限yy,改成mm,改成dd獲取天數

SELECT datediff(mm,getdate(),'2012-9-2')

select datename(dw,getdate())//返回日期的周幾切記返回的是字符串

sign(@A)若符號是-,返回-1,+返回1,0返回0

sqrt(16),平方根4;

round();近似值

power(2,4);2sup4;

floor(a):小於等於a的最小整數;

ceiling:大於或等與最大整數值;

60-100的隨機數:rand()*40+60便可;

select convert(INT,'123') 或 select cast('123' as int)

select 1+'2'//返回3;

datalength();返回字節數,一個漢字兩個字節,可是len()返回個數

system_user登錄名;

select isnull(mess,'哈哈') from xin:若是爲空的話改成哈哈輸出

 set @str2=substring(@str1,0,@num)、

--------

min,max,avg,count,;

----------分組查詢:多列分組;

group by id,iid,但二二對應,順序不變

select distinct GTime from Grade

param[4].Value!=DBNull.Value

 

 set @stuid=rtrim(@bubianid)+convert(char(10),@beginstuid)

----------內聯:左右兩個表都存在才顯示

select identity(1,1) as t;表示列的行數;

SQL Server判斷對象是否存在 (if exists (select * from sysobjects )(轉)

 

 

1 判斷數據庫是否存在

Sql代碼

if exists (select * from sys.databases where name = ’數據庫名’) 

  drop database [數據庫名]  if exists (select * from sys.databases where name = ’數據庫名’)

  drop database [數據庫名]

2 判斷表是否存在

Sql代碼

if exists (select * from sysobjects where id = object_id(N’[表名]’) and OBJECTPROPERTY(id, N’IsUserTable’) = 1) 

  drop table [表名]  if exists (select * from sysobjects where id = object_id(N’[表名]’) and OBJECTPROPERTY(id, N’IsUserTable’) = 1)

  drop table [表名]

3 判斷存儲過程是否存在

Sql代碼

if exists (select * from sysobjects where id = object_id(N’[存儲過程名]’) and OBJECTPROPERTY(id, N’IsProcedure’) = 1) 

  drop procedure [存儲過程名]  if exists (select * from sysobjects where id = object_id(N’[存儲過程名]’) and OBJECTPROPERTY(id, N’IsProcedure’) = 1)

  drop procedure [存儲過程名]

4 判斷臨時表是否存在

Sql代碼

if object_id(’tempdb..#臨時表名’) is not null   

  drop table #臨時表名  if object_id(’tempdb..#臨時表名’) is not null 

  drop table #臨時表名

5 判斷視圖是否存在

Sql代碼

--SQL Server 2000  

IF EXISTS (SELECT * FROM sysviews WHERE object_id = ’[dbo].[視圖名]’ 

--SQL Server 2005  

IF EXISTS (SELECT * FROM sys.views WHERE object_id = ’[dbo].[視圖名]’  --SQL Server 2000

IF EXISTS (SELECT * FROM sysviews WHERE object_id = ’[dbo].[視圖名]’

--SQL Server 2005

IF EXISTS (SELECT * FROM sys.views WHERE object_id = ’[dbo].[視圖名]’

6 判斷函數是否存在

Sql代碼

--  判斷要建立的函數名是否存在   

  if exists (select * from dbo.sysobjects where id = object_id(N’[dbo].[函數名]’) and xtype in (N’FN’, N’IF’, N’TF’))   

  drop function [dbo].[函數名]    --  判斷要建立的函數名是否存在 

  if exists (select * from dbo.sysobjects where id = object_id(N’[dbo].[函數名]’) and xtype in (N’FN’, N’IF’, N’TF’)) 

  drop function [dbo].[函數名] 

7 獲取用戶建立的對象信息

Sql代碼

SELECT [name],[id],crdate FROM sysobjects where xtype=’U’ 

 

/* 

xtype 的表示參數類型,一般包括以下這些 

C = CHECK 約束 

D = 默認值或 DEFAULT 約束 

F = FOREIGN KEY 約束 

L = 日誌 

FN = 標量函數 

IF = 內嵌表函數 

P = 存儲過程 

PK = PRIMARY KEY 約束(類型是 K) 

RF = 複製篩選存儲過程 

S = 系統表 

TF = 表函數 

TR = 觸發器 

U = 用戶表 

UQ = UNIQUE 約束(類型是 K) 

V = 視圖 

X = 擴展存儲過程 

*/  SELECT [name],[id],crdate FROM sysobjects where xtype=’U’

/*

xtype 的表示參數類型,一般包括以下這些

C = CHECK 約束

D = 默認值或 DEFAULT 約束

F = FOREIGN KEY 約束

L = 日誌

FN = 標量函數

IF = 內嵌表函數

P = 存儲過程

PK = PRIMARY KEY 約束(類型是 K)

RF = 複製篩選存儲過程

S = 系統表

TF = 表函數

TR = 觸發器

U = 用戶表

UQ = UNIQUE 約束(類型是 K)

V = 視圖

X = 擴展存儲過程

*/

8 判斷列是否存在

Sql代碼

if exists(select * from syscolumns where id=object_id(’表名’) and name=’列名’) 

  alter table 表名 drop column 列名  if exists(select * from syscolumns where id=object_id(’表名’) and name=’列名’)

  alter table 表名 drop column 列名

9 判斷列是否自增列

Sql代碼

if columnproperty(object_id(’table’),’col’,’IsIdentity’)=1 

  print ’自增列’ 

else 

  print ’不是自增列’ 

 

SELECT * FROM sys.columns WHERE object_id=OBJECT_ID(’表名’) 

AND is_identity=1  if columnproperty(object_id(’table’),’col’,’IsIdentity’)=1

  print ’自增列’

else

  print ’不是自增列’

SELECT * FROM sys.columns WHERE object_id=OBJECT_ID(’表名’)

AND is_identity=1

10 判斷表中是否存在索引

Sql代碼

if exists(select * from sysindexes where id=object_id(’表名’) and name=’索引名’)   

  print  ’存在’   

else   

  print  ’不存在  if exists(select * from sysindexes where id=object_id(’表名’) and name=’索引名’) 

  print  ’存在’ 

else 

  print  ’不存在

11 查看數據庫中對象

Sql代碼

SELECT * FROM sys.sysobjects WHERE name=’對象名’  SELECT * FROM sys.sysobjects WHERE name=’對象名’

//sql語句優化:

1.儘可能使用存儲過程

2.使用存儲過程創建表外鏈是最好全部的存儲過程鎖定表的順序最好同樣,不然會出現死鎖現象;

3.避免類型轉換;

4.在一個存儲過程當中使用的結果儘可能保存到一個變量中去,這樣減小運算;

5.儘可能少使用count的函數,消耗內存;

6.存儲過程可進行復雜運算減小網絡傳輸;

--------------------------------------------like裏面放入變量

SELECT * FROM Info

 WHERE

   Name

   LIKE '%'+@a+'%'

---------------------------------------------多重選擇!判斷

!第一種用法;select CASE WHEN id=1 THEN 'sdfsdf' WHEN id=2 THEN 'rrsdfs' END as 'asdad'

FROM Info

!第二種用法:

------------------------------------------------------

三範式是一我的根據數學函數提出的:是一種具備最小冗餘的表結構

1.第一範式:確保每列的原子行;每一個列不可再分割,固然也不要分割的太死;

2.凡是多對多關係,都轉爲兩個一對多關係,從而增添一個關聯表;

3.第二範式要求每個表只作一件事情;重要:表中除了主鍵列之外的其餘列

都要依賴於主鍵列;(強調依賴關係)

4第三範式:在一個表中消除間接依賴;好比有用戶ID就不須要有用用用戶姓名了;我勒個去

如何保證表中不能插入相同數據行;(強調直接依賴關係;)

a 1 2 3

a 1 2 4

不能有a 1 2 3,a 1 3 不能再出現;

-----------------------------------------子查詢時,當在多個結果中劃等號能夠用in

select ----where id in (select id from ----)

----------------

if(select Id from b where id>80)//是錯誤的,if只識別一個返回值,因此改成

if(select Max(id) from b where id>80)便可;

if exists()//能夠判斷返回多個返回值;

----------------事務

begin transaction

 

若是沒問題的話提交事務;

commit transaction

回滾事務

rollback transaction;

-----------------------------------------------------------------------------------

===不僅是數值相等,數據類型也要相同

 

雖然JS是弱類型,不用明確的定義數據類型,並且JS會根據狀況自動轉化類型.可是仍是有數據類型的

isex char(4) check(isex='男' or isex='女'),

  univer char(30) default '瀋陽理工大學應用技術學院' 

--計算時間差,運動會倒計時

--datediff(獲取的時間部分,減得時間,被減的時間)

select datediff(day,getdate(),'2011-5-27')

select datediff(year,'1991-03-03',getdate())--後面的減去中間的就是生日

select id,upper(name) as lname from stu

select id,lower(name) as lname from stu

標量函數

create function fn_newRegion(@input nvarchar(30))

returns nvarchar(30)--指明返回值的數據類型returns記住要加s

as

  begin

  if @input is null

  set @input='not know'

  return @input

  end

 

 

select * from authors

select count(distinct city) from authors

回滾事務

begin

      raiserror('score is between0 and 100',16,1)

      rollback transaction--回滾事物,取消操做

end

 

 

ALTER FUNCTION [dbo].[funGenerateBillCode](@name varchar(10),@time datetime,@time1 datetime)

         RETURNS varCHAR(20)

         AS

          BEGIN

         declare @e varchar(20)

         declare @a int

         declare @b int

         declare @c varchar(20)

         SELECT @a=DATEPART(year,@time)

         SELECT @b=DATEPART(month,@time1)

         set @c=convert(varchar(20),@a*100+@b)

         set @e=@c+@name

             return @e

         END

 

 

 

         command.Parameters.Add(

                                     new SqlParameter("ReturnValue", SqlDbType.Int, 4,

                                     ParameterDirection.ReturnValue, false, 0, 0,

                                     string.Empty, DataRowVersion.Default, null));

 

------存儲過程「、

CREATE PROCEDURE [dbo].[uspCreateBillDispense]

         (

         @billType                                      VARCHAR(50),          --票據類型

    @billStartCode                           VARCHAR(50),     --票據開始時間

         @billEndCode                    VARCHAR(50),             --票據結束時間

         @receiveBillperson     VARCHAR(50),        --領票人

         @acceptStation          VARCHAR(50),        --接貨點

         @receiveBillTime        DATETIME,           --領票時間

         @releaseperson          VARCHAR(50),        --分發人

         @PKID                   INT OUTPUT          --票據ID

                  

)

 

 

 

CREATE FUNCTION [dbo].[funGenerateBillCode](@billType,@billCode,@receiveBillTime)

         RETURNS CHAR(11)

         AS

          BEGIN

         DECLARE @code     CHAR(11)

            IF @billType='運貨單'

            SET @code=@code+'C'

         ELSE

         SET @code=@code+'R'

         END

 

 

 

/*********************************************************************************

*過程名稱 : uspCreateBillDispense

*功能描述 : 根據登陸ID, 獲取一條用戶的信息

*輸入參數 :

          @billCode   VARCHAR(50),       ---票據開始號或票據結束號

           @billType   VARCHAR(50),       ---票據類型

           @receiveBillTime DATETIME      ---領票時間

*輸出參數 :

         無

*返 回 值 :

         0 - 不存在

          1-存在

*做     者 : 郭澤峯

*建立日期 : 2011-12-27    

***********************************************************************************/

 

CREATE PROCEDURE [dbo].[uspExistBillDispense]

         (

           @billCode   VARCHAR(50),       ---票據開始號或票據結束號

           @billType   VARCHAR(50),       ---票據類型

           @receiveBillTime DATETIME      ---領票時間

         )

AS

         /* SET NOCOUNT ON */

         RETURN

 

 

-----------------

CREATE PROCEDURE IsFocus     @a INT,     @b INTASBEGIN    SET NOCOUNT ON;       DECLARE @res bit      IF EXISTS(SELECT * FROM dbo.foucs WHERE [user1]=@a AND [user2]=@b)         SET @res=1     ELSE        SET @res=0     SELECT @res AS res ENDGO

 

---------------------數據庫分頁效果

CREATE   PROC   sp_PageView

@tbname           sysname,                       --要分頁顯示的表名

@FieldKey       nvarchar(1000),     --用於定位記錄的主鍵(唯一鍵)字段,能夠是逗號分隔的多個字段

@PageCurrent   int=1,                       --要顯示的頁碼

@PageSize       int=10,                         --每頁的大小(記錄數)

@FieldShow   nvarchar(1000)= ' ',     --以逗號分隔的要顯示的字段列表,若是不指定,則顯示全部字段

@FieldOrder   nvarchar(1000)= ' ',     --以逗號分隔的排序字段列表,能夠指定在字段後面指定DESC/ASC

                                                                                    用於指定排序順序

@Where         nvarchar(1000)= ' ',   --查詢條件

@PageCount   int   OUTPUT                   --總頁數

AS

SET   NOCOUNT   ON

--檢查對象是否有效

IF   OBJECT_ID(@tbname)   IS   NULL

BEGIN

RAISERROR(N '對象 "%s "不存在 ',1,16,@tbname)

RETURN

END

IF   OBJECTPROPERTY(OBJECT_ID(@tbname),N 'IsTable ')=0

AND   OBJECTPROPERTY(OBJECT_ID(@tbname),N 'IsView ')=0

AND   OBJECTPROPERTY(OBJECT_ID(@tbname),N 'IsTableFunction ')=0

BEGIN

RAISERROR(N ' "%s "不是表、視圖或者表值函數 ',1,16,@tbname)

RETURN

END

 

--分頁字段檢查

IF   ISNULL(@FieldKey,N ' ')= ' '

BEGIN

RAISERROR(N '分頁處理須要主鍵(或者唯一鍵) ',1,16)

RETURN

END

 

--其餘參數檢查及規範

IF   ISNULL(@PageCurrent,0) <1   SET   @PageCurrent=1

IF   ISNULL(@PageSize,0) <1   SET   @PageSize=10

IF   ISNULL(@FieldShow,N ' ')=N ' '   SET   @FieldShow=N '* '

IF   ISNULL(@FieldOrder,N ' ')=N ' '

SET   @FieldOrder=N ' '

ELSE

SET   @FieldOrder=N 'ORDER   BY   '+LTRIM(@FieldOrder)

IF   ISNULL(@Where,N ' ')=N ' '

SET   @Where=N ' '

ELSE

SET   @Where=N 'WHERE   ( '+@Where+N ') '

 

--若是@PageCount爲NULL值,則計算總頁數(這樣設計能夠只在第一次計算總頁數,之後調用時,把總頁數傳回給存儲過程,避免再次計算總頁數,對於不想計算總頁數的處理而言,能夠給@PageCount賦值)

IF   @PageCount   IS   NULL

BEGIN

DECLARE   @sql   nvarchar(4000)

SET   @sql=N 'SELECT   @PageCount=COUNT(*) '

+N '   FROM   '+@tbname

+N '   '+@Where

EXEC   sp_executesql   @sql,N '@PageCount   int   OUTPUT ',@PageCount   OUTPUT

SET   @PageCount=(@PageCount+@PageSize-1)/@PageSize

END

 

--計算分頁顯示的TOPN值

DECLARE   @TopN   varchar(20),@TopN1   varchar(20)

SELECT   @TopN=@PageSize,

@TopN1=(@PageCurrent-1)*@PageSize

 

--第一頁直接顯示

IF   @PageCurrent=1

EXEC(N 'SELECT   TOP   '+@TopN

+N '   '+@FieldShow

+N '   FROM   '+@tbname

+N '   '+@Where

+N '   '+@FieldOrder)

ELSE

BEGIN

--處理別名

IF   @FieldShow=N '* '

SET   @FieldShow=N 'a.* '

 

--生成主鍵(唯一鍵)處理條件

DECLARE   @Where1   nvarchar(4000),@Where2   nvarchar(4000),

@s   nvarchar(1000),@Field   sysname

SELECT   @Where1=N ' ',@Where2=N ' ',@s=@FieldKey

WHILE   CHARINDEX(N ', ',@s)> 0

SELECT   @Field=LEFT(@s,CHARINDEX(N ', ',@s)-1),

@s=STUFF(@s,1,CHARINDEX(N ', ',@s),N ' '),

@Where1=@Where1+N '   AND   a. '+@Field+N '=b. '+@Field,

@Where2=@Where2+N '   AND   b. '+@Field+N '   IS   NULL ',

@Where=REPLACE(@Where,@Field,N 'a. '+@Field),

@FieldOrder=REPLACE(@FieldOrder,@Field,N 'a. '+@Field),

@FieldShow=REPLACE(@FieldShow,@Field,N 'a. '+@Field)

SELECT   @Where=REPLACE(@Where,@s,N 'a. '+@s),

@FieldOrder=REPLACE(@FieldOrder,@s,N 'a. '+@s),

@FieldShow=REPLACE(@FieldShow,@s,N 'a. '+@s),

@Where1=STUFF(@Where1+N '   AND   a. '+@s+N '=b. '+@s,1,5,N ' '),

@Where2=CASE

WHEN   @Where= ' '   THEN   N 'WHERE   ( '

ELSE   @Where+N '   AND   ( '

END+N 'b. '+@s+N '   IS   NULL '+@Where2+N ') '

 

--執行查詢

EXEC(N 'SELECT   TOP   '+@TopN

+N '   '+@FieldShow

+N '   FROM   '+@tbname

+N '   a   LEFT   JOIN(SELECT   TOP   '+@TopN1

+N '   '+@FieldKey

+N '   FROM   '+@tbname

+N '   a   '+@Where

+N '   '+@FieldOrder

+N ')b   ON   '+@Where1

+N '   '+@Where2

+N '   '+@FieldOrder)

END

----------------------------------數據庫時間函數的調用

1. 當前系統日期、時間

select getdate()

2. dateadd 在向指定日期加上一段時間的基礎上,返回新的 datetime 值

例如:向日期加上2天

select dateadd(day,2,'2004-10-15') --返回:2004-10-17 00:00:00.000

 

3. datediff 返回跨兩個指定日期的日期和時間邊界數。

select datediff(day,'2004-09-01','2004-09-18') --返回:17

 

4. datepart 返回表明指定日期的指定日期部分的整數。

SELECT DATEPART(month, '2004-10-15') --返回 10

 

5. datename 返回表明指定日期的指定日期部分的字符串

SELECT datename(weekday, '2004-10-15') --返回:星期五

 

6. day(), month(),year() --能夠與datepart對照一下

 

select 當前日期=convert(varchar(10),getdate(),120)

,當前時間=convert(varchar(8),getdate(),114)

 

select datename(dw,'2004-10-15')

 

select 本年第多少周=datename(week,'2004-10-15')

,今天是周幾=datename(weekday,'2004-10-15')

 

函數 參數/功能

GetDate( ) 返回系統目前的日期與時間

DateDiff (interval,date1,date2) 以interval 指定的方式,返回date2 與date1兩個日期之間的差值 date2-date1

DateAdd (interval,number,date) 以interval指定的方式,加上number以後的日期

DatePart (interval,date) 返回日期date中,interval指定部分所對應的整數值

DateName (interval,date) 返回日期date中,interval指定部分所對應的字符串名稱

 

參數 interval的設定值以下:

 

值 縮 寫(Sql Server) Access 和 ASP 說明

Year Yy yyyy 年 1753 ~ 9999

Quarter Qq q 季 1 ~ 4

Month Mm m 月1 ~ 12

Day of year Dy y 一年的日數,一年中的第幾日 1-366

Day Dd d 日,1-31

Weekday Dw w 一週的日數,一週中的第幾日 1-7

Week Wk ww 周,一年中的第幾周 0 ~ 51

Hour Hh h 時0 ~ 23

Minute Mi n 分鐘0 ~ 59

Second Ss s 秒 0 ~ 59

Millisecond Ms - 毫秒 0 ~ 999

 

access 和 asp 中用date()和now()取得系統日期時間;其中DateDiff,DateAdd,DatePart也同是能用於Access和asp中,這些函數的用法也相似

 

舉例:

1.GetDate() 用於sql server :select GetDate()

 

2.DateDiff('s','2005-07-20','2005-7-25 22:56:32')返回值爲 514592 秒

DateDiff('d','2005-07-20','2005-7-25 22:56:32')返回值爲 5 天

 

3.DatePart('w','2005-7-25 22:56:32')返回值爲 2 即星期一(週日爲1,週六爲7)

DatePart('d','2005-7-25 22:56:32')返回值爲 25即25號

DatePart('y','2005-7-25 22:56:32')返回值爲 206即這一年中第206天

DatePart('yyyy','2005-7-25 22:56:32')返回值爲 2005即2005年

 

SQL Server DATEPART() 函數返回 SQLServer datetime 字段的一部分。

 

SQL Server DATEPART() 函數的語法是:

DATEPART(portion, datetime)

其中 datetime 是 SQLServer datetime 字段和部分的名稱是下列之一: Ms for Milliseconds

Yy for Year

Qq for Quarter of the Year

Mm for Month

Dy for the Day of the Year

Dd for Day of the Month

Wk for Week

Dw for the Day of the Week

Hh for Hour

Mi for Minute

Ss for Second

 

詳細的說明:

 

一般,你須要得到當前日期和計算一些其餘的日期,例如,你的程序可能須要判斷一個月的第一天或者最後一天。大家大部分人大概都知道怎樣把日期進行分割(年、月、日等),而後僅僅用分割出來的年、月、日等放在幾個函數中計算出本身所須要的日期!在這篇文章裏,我將告訴你如何使用DATEADD和DATEDIFF函數來計算出在你的程序中可能你要用到的一些不一樣日期。

在使用本文中的例子以前,你必須注意如下的問題。大部分可能不是全部例子在不一樣的機器上執行的結果可能不同,這徹底由哪一天是一個星期的第一天這個設置決定。第一天(DATEFIRST)設定決定了你的系統使用哪一天做爲一週的第一天。全部如下的例子都是以星期天做爲一週的第一天來創建,也就是第一天設置爲7。假如你的第一天設置不同,你可能須要調整這些例子,使它和不一樣的第一天設置相符合。你能夠經過@@DATEFIRST函數來檢查第一天設置。

 

爲了理解這些例子,咱們先複習一下DATEDIFF和DATEADD函數。DATEDIFF函數計算兩個日期之間的小時、天、周、月、年等時間間隔總數。DATEADD函數計算一個日期經過給時間間隔加減來得到一個新的日期。要了解更多的DATEDIFF和DATEADD函數以及時間間隔能夠閱讀微軟聯機幫助。

 

使用DATEDIFF和DATEADD函數來計算日期,和原本從當前日期轉換到你須要的日期的考慮方法有點不一樣。你必須從時間間隔這個方面來考慮。好比,從當前日期到你要獲得的日期之間有多少時間間隔,或者,從今天到某一天(好比1900-1-1)之間有多少時間間隔,等等。理解怎樣着眼於時間間隔有助於你輕鬆的理解個人不一樣的日期計算例子。

 

一個月的第一天

 

第一個例子,我將告訴你如何從當前日期去這個月的最後一天。請注意:這個例子以及這篇文章中的其餘例子都將只使用DATEDIFF和DATEADD函數來計算咱們想要的日期。每個例子都將經過計算但前的時間間隔,而後進行加減來獲得想要計算的日期。

 

這是計算一個月第一天的SQL 腳本:

SELECT DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)

 

咱們把這個語句分開來看看它是如何工做的。最核心的函數是getdate(),大部分人都知道這個是返回當前的日期和時間的函數。下一個執行的函數DATEDIFF(mm,0,getdate())是計算當前日期和「1900-01-01 00:00:00.000」這個日期之間的月數。記住:時期和時間變量和毫秒同樣是從「1900-01-01 00:00:00.000」開始計算的。這就是爲何你能夠在DATEDIFF函數中指定第一個時間表達式爲「0」。下一個函數是DATEADD,增長當前日期到「1900-01-01」的月數。經過增長預約義的日期「1900-01-01」和當前日期的月數,咱們能夠得到這個月的第一天。另外,計算出來的日期的時間部分將會是「00:00:00.000」。

 

這個計算的技巧是先計算當前日期到「1900-01-01」的時間間隔數,而後把它加到「1900-01-01」上來得到特殊的日期,這個技巧能夠用來計算不少不一樣的日期。下一個例子也是用這個技巧從當前日期來產生不一樣的日期。

 

本週的星期一

 

這裏我是用周(wk)的時間間隔來計算哪一天是本週的星期一。

 

SELECT DATEADD(wk, DATEDIFF(wk,0,getdate()), 0)

 

一年的第一天

 

如今用年(yy)的時間間隔來顯示這一年的第一天。

 

SELECT DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)

 

季度的第一天

 

假如你要計算這個季度的第一天,這個例子告訴你該如何作。

 

SELECT DATEADD(qq, DATEDIFF(qq,0,getdate()), 0)

 

當天的半夜

 

曾經須要經過getdate()函數爲了返回時間值截掉時間部分,就會考慮到當前日期是否是在半夜。假如這樣,這個例子使用DATEDIFF和DATEADD函數來得到半夜的時間點。

 

SELECT DATEADD(dd, DATEDIFF(dd,0,getdate()), 0)

 

深刻DATEDIFF和DATEADD函數計算

 

你能夠明白,經過使用簡單的DATEDIFF和DATEADD函數計算,你能夠發現不少不一樣的可能有意義的日期。

 

目前爲止的全部例子只是僅僅計算當前的時間和「1900-01-01」之間的時間間隔數量,而後把它加到「1900-01-01」的時間間隔上來計算出日期。假定你修改時間間隔的數量,或者使用不一樣的時間間隔來調用DATEADD函數,或者減去時間間隔而不是增長,那麼經過這些小的調整你能夠發現和多不一樣的日期。

 

這裏有四個例子使用另一個DATEADD函數來計算最後一天來分別替換DATEADD函數先後兩個時間間隔。

 

上個月的最後一天

 

這是一個計算上個月最後一天的例子。它經過從一個月的最後一天這個例子上減去3毫秒來得到。有一點要記住,在Sql Server中時間是精確到3毫秒。這就是爲何我須要減去3毫秒來得到我要的日期和時間。

 

SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(mm,0,getdate()), 0))

 

計算出來的日期的時間部分包含了一個Sql Server能夠記錄的一天的最後時刻(「23:59:59:997」)的時間。

 

去年的最後一天

 

鏈接上面的例子,爲了要獲得去年的最後一天,你須要在今年的第一天上減去3毫秒。

 

SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0))

 

本月的最後一天

 

如今,爲了得到本月的最後一天,我須要稍微修改一下得到上個月的最後一天的語句。修改須要給用DATEDIFF比較當前日期和「1900-01-01」返回的時間間隔上加1。經過加1個月,我計算出下個月的第一天,而後減去3毫秒,這樣就計算出了這個月的最後一天。這是計算本月最後一天的SQL腳本。

 

SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0))

 

本年的最後一天

 

你如今應該掌握這個的作法,這是計算本年最後一天腳本

 

SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0))

 

本月的第一個星期一

 

好了,如今是最後一個例子。這裏我要計算這個月的第一個星期一。這是計算的腳本。

 

select DATEADD(wk, DATEDIFF(wk,0,

dateadd(dd,6-datepart(day,getdate()),getdate())), 0)

-------------------------------------------------------------sql中根據字段不一樣sum統計

sum(case LeiBie when '階段計劃' then SL else 0 end) as 'JDSL',

------------------在某字段後面加字符是沒有問題的

use cc

SELECT Name+'hhh',Sex,sum(Score) as 'ddd' from Score

GROUP BY Name,sex WITH ROLLUP

-----------------------------js依次打印文字;

it=0;

function typeit() {

    var word = mytext.charAt(it, idstr);

    if (it < mytext.length - 1) {

        it++

        t = setTimeout("typeit()", Math.random() * 10);

    }

    else {

        clearTimeout(t);

        it = 0;

        i++;

        start();

    }

------------------------------js若在頁面已加載就開始調用服務器端控件,對報關於對象的錯!

解決方案,經過後臺註冊腳本方法間接調用前臺方法;

 

-----js向標記中添加標記

累加$("#content").append("<img src='../img/bg2.jpg'/>");不累加:.html();

或者是js:.innerHTML=;累加:+=innerHTML;

----------------要讓出連接以外的有北京顏色顯示須要

  $("li").mouseenter(function () {

        $(this).attr("background-color", "#ccff66");

    });

li:hover

{

         /*background-image: url(img/menu2.gif);*/

         cursor: pointer;

         background-color:#ccff66;

}同時使用纔有效果;

------------------------------frame去掉邊框:

<iframe frameborder="0" >

---------------------------------------------------------:

decimal(18,6);

-----------------------------虛擬表:#表名;

---timestamp:時間戳,二進制數據;

----WAITFOR delay '00:00:005':數據庫時間延遲

---SELECT @@rowcount;返回上一操做所影響的行數,若是大於0,可判斷操做是否成功;

處理併發:悲觀:(事務+鎖);樂觀(時間戳)

悲觀處理方式是 採用SQLSERVER數據庫中「事務+鎖」!(隔離級別總共四種默認level1)會產生髒讀;

 

  先上僞代碼再解釋:

 

  1.先解釋2個要用到的鎖

 

  SELECT * FROM table WITH (HOLDLOCK) 其餘事務能夠讀取表,但不能更新刪除 (避免不可重複讀),避免統一事務屢次讀取結果一致防止他人修改;

  SELECT * FROM table WITH (TABLOCKX) 其餘事務不能讀取表,更新和刪除

   SELECT * FROM table WITH (updLOCK) 其餘事務能讀取表,但不能更新

 

 

  PS:這2個是表級鎖,要鎖行加上SQL過濾條件便可。數據庫的默認隔離級別是readcommit,(更改的事務未完成,其它不能讀取)

    也就是level1;,可讀:能夠查詢+with(holdlock),若想不可讀,with(tablockx)

  2.樂觀:事務+時間戳;

 

------------------如何避免死鎖 1 使用事務時,儘可能縮短事務的邏輯處理過程,及早提交或回滾事務;

 2 設置死鎖超時參數爲合理範圍,如:3分鐘-10分種;超過期間,自動放棄本次操做,避免進程懸掛;

3 優化程序,檢查並避免死鎖現象出現; 4 .對全部的腳本和SP都要仔細測試,在正是版本以前。

 5 全部的SP都要有錯誤處理(經過@error) 6 通常不要修改SQL SERVER事務的默認級別。

不推薦強行加鎖

------------------------------------時間戳:(微軟建議用rowversion)

convert(bigint,time),對應c#int64進行比較便可;

--------------------別面內存泄露的方法,在一個類中建立另外一個類的實例時,當不用了,賦值null,這樣就告訴系統,能夠回收了;

------恢復數據庫:

restore database guo from disk='路徑備份' with recovery

------------------經典的dispose();垃圾回收gc(回收時將對象賦值爲null),告訴回收器,我已經不被引用了,隨時清理;

    class A:IDisposable

    {

        private bool isDisposed = false;

        public void Dispose()

        {

            Dispose(true);

            GC.SuppressFinalize(this);//告訴回收器清理已完成,無需調用析構函數;

        }

        protected virtual void Dispose(bool disposing)

        {

            if (!isDisposed)

            {

                if (disposing)

                {

                    //釋放託管資源

                }

                //釋放非託管資源

            }

            isDisposed = true;

        }

        ~A()//有回收期調用,不固定;

        {

            Dispose(false);

            //主要清理非託管;

        }

    }

-------------------------------------文件流,數據庫的鏈接,系統的窗口句柄,打印機資源等等網絡鏈接,這些是非託管資源;

-----產生內存泄露的緣由:

文件流,數據庫的鏈接,系統的窗口句柄,打印機資源等等

------------

1.內存泄露的緣由:

!使用靜態引用;

!爲退訂的事件;

!爲調用的Dispose方法;

!使用不完全的Dispose方法;

等等;

內存泄露:Fabrice稱,內存泄漏發生在一塊內存不 再被使用,但卻依然被程序所引用時

使用靜態引用

未退訂的事件-做者認爲這是最多見的內存泄漏緣由

未退訂的靜態事件

未調用Dispose方法

使用不完全的Dispose方法

在Windows Forms中對BindingSource的誤用

未在WorkItem/CAB上調用Remove

------------

對象的建立者或擁有者負責銷燬對象,而不是使用者

當再也不須要一個事件訂閱者時退訂此事件,爲確保安全能夠在Dispose方法中退訂

當對象再也不觸發事件時,應該將對象設爲null來移除全部的事件訂閱者

當模型和視圖引用同一個對象時,推薦給視圖傳遞一個此對象的克隆,以防止沒法追蹤誰在使用哪一個對象

對系統資源的訪問應該包裝在using塊中,這將在代碼執行後強制執行Dispose

---------------------------

用上面的SQL語句還原備份數據庫時,數據庫的狀態老是「正在還原」,使得不能對它進行其餘操做。

 

解決方案:「RESTORE DATABASE " + dbName + " From disk='" + filePath + "' WITH REPLACE,RECOVERY ";

-----------通常還原數據庫的話是 with replace;

----------------備份知識

一、SQL數據庫恢復模型

----------------------------------------------------------------------

1)徹底恢復模型

-----------------

(1)備份時要備份數據庫的數據文件和日誌文件

(2)還原時使用數據庫的備份的數據文件副本和所有日誌信息來恢復數據庫。

(3)能還原所有數據,並能夠將數據庫恢復到任意指定的時刻。

(4)爲保證明現即時點恢復,對數據庫的全部*做都將完整地記入日誌,這樣,日誌佔用空間較大,對性能也有所影響。

------------------

(2)大容量日誌記錄恢復模型

------------------

(1)備份時要備份數據庫的數據文件和日誌文件

(2)還原時使用數據庫的備份的數據文件副本和所有日誌信息來恢復數據庫。

(3)日誌中不記錄*做細節(如select into、create index等),而只記錄*做的最終結果,所以佔用日誌空間小。

(4)只支持將數據庫還原到事務日誌備份的時刻,而不支持即時點恢復,所以可能產生數據丟失。

-------------------

(3)簡單恢復模型

-------------------

(1)備份時只備份數據文件,還原時也用備份的數據文件恢復數據庫。

(2)只能將數據恢復到數據文件備份的時刻,可能產生最多的數據丟失。

(3)不適於生產系統和大規模*做環境下選用。

-----------------------------------------

alter database d1 set recovery simple     --設置數據庫恢復模型

alter database d1 set recovery bulk_logged

alter database d1 set recovery full

----------------------------------------------------------------------

二、備份設備

----------------------------------------------------------------------

1)物理設備

---------------------------

disk:支持本地磁盤或者網絡備份

tape:支持磁帶機備份

name pipe:支持第三方備份軟件

---------------------------

2)邏輯設備

---------------------------

永久備份文件:能夠重複使用,應該在備份前建立。

臨時備份文件:用於一次性備份,在備份時建立。

-------------------------------------------------

exec sp_addumpdevice 'disk','bak2','e:\back_device\bak2.bak' --建立永久磁盤備份設備

exec sp_addumpdevice 'disk','bak3','e:\back_device\bak3.bak'

----------------------------------------------------------------------

exec sp_addumpdevice 'disk','bak4','\\sv2\backup\bak4.bak' --建立網絡永久磁盤備份設備

exec sp_addumpdevice 'disk','bak5','\\sv2\backup\bak5.bak'

----------------------------------------------------------------------

exec sp_dropdevice 'bak5'              --刪除備份設備

----------------------------------------------------------------------

backup database d3 to bak3      --將數據庫備份到備份設備

backup database d4 to bak4

----------------------------------------------------------------------

restore headeronly from bak2    --查看備份設備中的內容

----------------------------------------------------------------------

backup database d3 to disk='e:\back_file\d3.bak'    --將數據庫備份到臨時備份文件

backup database d4 to disk='e:\back_file\d4.bak'

----------------------------------------------------------------------

restore database d3 from bak3           --從備份設備還原數據庫      

restore database d4 from disk='e:\back_file\d4.bak' --從備份文件還原數據庫

----------------------------------------------------------------------

三、使用多個備份文件存儲備份

----------------------------------------------------------------------

1)SQL可同時向多個備份文件進行寫*做。若是把這些文件放到多個磁帶機或磁盤中,則可提升備份速度。

2)這多個備份文件必須用同業型的媒體,並放到一個媒體集中。

3)媒體集中的文件必須同時使用,而不能單獨使用。

4)能夠經過format命令將媒體集從新劃分,但原備份集中的數據不能再使用。

--------------------------------------------------------------------

backup database d4 to bak4,bak5,bak6 with medianame='bak456',format --備份D4並造成Media Set

backup database d3 to bak4      --失敗,因Media set中文件必須同時使用

backup database d3 to bak4,bak5,bak6    --成功,將D3也備份到Media Set中

restore headeronly from bak4,bak5,bak6--查看Media Set中的備分內容

----------------------------------------------------------------------

backup database d4 to bak4 with medianame='bak4',format     --從新劃分Media Set

backup database d3 to bak5,bak6 with medianame='bak56',format

----------------------------------------------------------------------

backup database d1 to bak1 with init     --with init重寫備份設備中內容

backup database d2 to bak1 with noinit --with noinit將內容追加到備份設備中

restore headeronly from bak1

----------------------------------------------------------------------

四、備份的方法

----------------------------------------------------------------------

1)徹底備份

-------------------------------------------

(1)是備份的基準。在作備份時第一次備份都建議使用徹底備份。

(2)徹底備份會備份數據庫的全部數據文件、數據對象和數據。

(3)會備份事務日誌中任何未提交的事務。由於已提交的事務已經寫入數據文件中。

--------------------------------------------

backup database d1 to bak1 with init     --徹底備份

backup database d1 to bak1 with noinit

----------------------------------------------------------------------

2)差別備份

---------------------------------------------

(1)基於徹底備份。

(2)備份自最近一次徹底備份以來的全部數據庫改變。

(3)恢復時,只應用最近一次徹底備份和最新的差別備份。

-----------------------------------------------

backup database d2 to bak2 with init,name='d2_full' --差別備份,第一次備份時應作徹底備份

create table b1(c1 int not null,c2 char(10) not null)

backup database d2 to bak2 with differential,name='d2_diff1'

insert b1 values(1,'a')

backup database d2 to bak2 with differential,name='d2_diff2'

insert b1 values(2,'b')

backup database d2 to bak2 with differential,name='d2_diff3'

insert b1 values(3,'c')

backup database d2 to bak2 with differential,name='d2_diff4'

restore headeronly from bak2

----------------------------------------------------------------------

3)事務日誌備份

-------------------------------------------------------------

(1)基於徹底備份。

(2)爲遞增備份,即備份從上一次備份以來到備份時所寫的事務日誌。

(3)容許恢復到故障時刻或者一個強制時間點。

(4)恢復時,須要應用徹底備份和徹底備份後的每第二天志備份。

-------------------------------------------------------------

backup database d3 to bak3 with init,name='d3_full' --日誌備份,第一次備份時應作徹底備份

create table b1(c1 int not null,c2 char(10) not null)

backup log d3 to bak3 with

insert b1 values(1,'a')

backup log d3 to bak3 with

insert b1 values(2,'b')

backup log d3 to bak3 with

insert b1 values(3,'c')

backup log d3 to bak3 with

restore headeronly from bak3

----------------------------------------------------------------------

create table b1(c1 int not null,c2 char(10) not null)    --Full+Log+Diff

backup log d4 to bak4 with

insert b1 values(1,'a')

backup log d4 to bak4 with

insert b1 values(2,'b')

backup database d4 to bak4 with differential,name='d4_diff1'

insert b1 values(3,'c')

backup log d4 to bak4 with

insert b1 values(4,'d')

backup log d4 to bak4 with

insert b1 values(5,'d')

backup database d4 to bak4 with differential,name='d4_diff2'

restore headeronly from bak4

----------------------------------------------------------------------

日誌清除

-----------------------------------------

1)若是日誌空間被填滿,數據庫將不能記錄修改。

2)數據庫在作徹底備份時日誌被截斷。

3)若是將'Trans log on checkpoint'選項設爲TRUE,則結果爲不保存日誌,即沒有日誌記錄,不建議使用。

4)with truncate_only和with no_log設置日誌滿時清除日誌

5)with no_truncate則能夠完整保存日誌,不清除,即便在數據文件已經損壞狀況下。主要用於數據庫出問題後在恢復前使用。能夠將數據還原到出故障的那一時刻。

-------------------------------------------

exec sp_dboption d3

exec sp_dboption

sp_dboption 'd3','trunc. log on chkpt.','true'     --設置自動清除數據庫日誌

sp_dboption 'd3','trunc. log on chkpt.','false'    --將自動清除數據庫日誌的選項去除

----------------------------------------------------------------------

backup log d4 with truncate_only    --設置D4日誌滿時清除日誌,並作清除記錄

----------------------------------------------------------------------

backup log d4 with no_log       --設置D4日誌滿時清除日誌,但不作清除記錄

----------------------------------------------------------------------

backup log d4 to bak4 with no_truncate--在D4數據庫損壞時立刻備份當前數據庫日誌(DEMO)

--------

使用no_truncate

徹底+修改1+差別+修改2+差別+修改3+中止SQL,刪除數據庫數據文件+重啓SQL

backup log no_truncate

再還原,可還原到修改3

-

-----------------------------數據庫恢復順序;

恢復數據庫中的數據,因此一般恢復的時間較長;先恢復最後一次全庫備份,再恢復最後一次差別備份,

再順序恢復最後一次差別備份之後進行的全部事務日誌備份

 

------------------數據庫四種備份;

1)徹底數據庫備份

   徹底數據庫備份是備份數據庫的全部表的數據及模式,以及對應的文件結構,包括對事務日誌中的事務進行備份。它能夠用做系統出現故障時恢復數據庫的基礎,也可用於在另一臺計算機上生成數據庫的副本。

  

(2)差別數據庫備份

   差別數據庫備份只記錄自上次徹底數據庫備份後發生變化的數據。差別備份的數據量比徹底備份的數據量小並且備份速度快,所以能夠更常常地備份。

   

(3)事務日誌備份

   事務日誌包含了自上次進行徹底數據庫備份、差別數據庫備份或事務日誌備份以來所完成的事務。可使用事務日誌備份將數據庫恢復到特定的即時點或恢復到故障點。

  

(4)數據庫文件和文件組備份

   只備份特定的文件或文件組,經常使用於超大型數據庫的備份。

---------------------------------------------------------數據併發,其多個用戶修改其它用戶正在使用的資源,併產生了必定的影響;

level0:(read uncommitted);修改未提交時,即可以讀取;---致使髒讀;解決方案:SET tran isolation level read uncommitted

個事務讀到另一個事務尚未提交的數據,咱們稱之爲髒讀

level1(read committed):(sql默認,(修改的過程當中不容許讀和修改)修改時(修改的進程還沒結束),另外一進程不能讀取)read committed;---致使不可重複讀:解決方案:讀取的事務中設置SET tran isolation level repeatable read;

一個事務前後讀取同一條記錄,但兩次讀取的數據不一樣,咱們稱之爲不可重複讀。讀取的過程當中(5秒鐘內),有其它事務修改了數據;

level2:(repeatable read),{原理:進行了s鎖,做用(小於with(holdlock),由於,le2不容許修改,因此不會出現不可重複讀,但出現幻讀,能夠插入,而holdlock不容許,這就是區別)

}解決方案:set tran isolation level serializable;:串行化(我的認爲是holdlock原理):

一個事務前後讀取一個範圍的記錄,但兩次讀取的紀錄數不一樣,咱們稱之爲幻象讀;(幻讀,讀的時候有數據插入,不可重複讀,讀的時候有數據修改)

level3:(serializable)串行化:避免了幻讀;

 

-------更改隔離類別;

BEGIN transaction

   SET tran isolation level read uncommitted

   update -----

IF @@error=0

  COMMIT transaction

else

ROLLBACK transaction

-------------------------------默認的level1:在修改中不容許修改和查詢,單容許插入;(插入不會引發不一致和完整性)

----------with(holdlock):查詢時,不容許修改和插入操做,容許查詢;

----------with(tablockx):查詢時什麼都不容許;

-------------------這兩個鎖只能應用在查詢上;

總結

事務隔離級別是經過數據庫的鎖機制來控制的,在不一樣的應用場景須要應用不一樣的事務隔離級別,

SQL Server默認的事務隔離級別是READ COMMITTED,默認的隔離級別,已經能夠知足咱們大部分應用的需求。

--------------------------行級鎖:鎖的粒度小;不想表級鎖,updlock,告訴你們,標記我整個事務將要更改,大家不要進行操做;

----------------------------------------------

--判斷是否數據庫存在某存儲過程

use master

select * from sysobjects where id = object_id(N'[killspid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1

--判斷是否存在某表

use cc

DECLARE

select * from sysobjects where id = object_id(N'[AA]') and OBJECTPROPERTY(id, N'IsUserTable') = 1

--判斷數據庫是否存在

select * from sys.databases where name ='CC'

--判斷是否存在臨時表,若存在刪除

CREATE table #a

(

  id int,

  name char(10)

)

SELECT * FROM #a

if object_id('tempdb..#a') is not null   

  drop table #a

--判斷表中某列是否存在

USE CC

select * from syscolumns where id=object_id('AA') and name='A'

-------------------------------------------------

 

 

-----------------------結束某數據庫的所有進程;(結束進程)遊標,查詢全部的數據庫鏈接進程;

USE master

DECLARE @dbname varchar(20)

SET @dbname='CC'

declare @sql   nvarchar(500)

declare @spid  int

set @sql='declare getspid cursor for select spid from sysprocesses where dbid=db_id('''+@dbname+''')'

EXEC(@sql)

open getspid

fetch next from getspid into @spid

while @@fetch_status =0

begin

   exec('kill '+@spid)

   fetch next from getspid into @spid

end

   close getspid

   deallocate getspid

--------------------------------------------獲取表中的列名;

dr.GetName(1);sqldatareader;

---------------------------緩存:cache;

public static object GetCache(string CacheKey)

                   {

                            System.Web.Caching.Cache objCache = HttpRuntime.Cache;

                            return objCache[CacheKey];

                   }

 

                   /// <summary>

                   /// 設置當前應用程序指定CacheKey的Cache值

                   /// </summary>

                   /// <param name="CacheKey"></param>

                   /// <param name="objObject"></param>

                   public static void SetCache(string CacheKey, object objObject)

                  {

                            System.Web.Caching.Cache objCache = HttpRuntime.Cache;

                            objCache.Insert(CacheKey, objObject);

                   }

----------------------------將對象序列化;

  User u = new User() {  Age=1,Name="郭澤峯"};

        var str = new  System.Web.Script.Serialization.JavaScriptSerializer();

        var ff=str.Serialize(u);//字符串形式的json對象;

        TextBox1.Text = ff;

------------------------------ ScriptManager.RegisterStartupScript的命名空間:web.extension;中;

---------------------加入收藏夾;

  <li class="h_text"><a href="javascript:save();">加入收藏</a></li>

 window.external.addFavorite('http://zfsoftware.tk', '麥兜網')

----------設爲首頁;

<li class="h_text"><a href="#" onClick="this.style.behavior='url(#default#homepage)';this.setHomePage('http://zfsoftware.tk')">設爲首頁</a></li>

-------------------------------------------------------ajax測試服務webjison

(1)調用web服務的user對象;提取方法guo千萬不要加();success:guo;

            $.ajax({

                type: "Post",

                url: "WebService.asmx/getuser",

                contentType: "application/json; charset=utf-8",

                dataType: "json",

                success: function (obj) {

                    alert(obj.d.Name);

                },

                error: function (err) {

                    alert(err);

                }

            });

        -----------自帶的方法;(沒有d),

        WebService.getuser(function (result) {

                alert(result.Name);

             },null,null)

(2)--------------調用list<int>,數組

               alert(obj.d[0]);

------------------

               alert(result[1]);

(3)----------調用idictionary集合;

                 alert(obj.d[「a」].Name);

------------------

               alert(result["a"].Name);

(4)調用list<user>對象;

             alert(obj.d[0].Name);

            for (var s in obj.d) {

                $("#guo").append("<tr><td>"+obj.d[s].Name+"</td></tr>");

            }

----------------------------------序列化;(json)

   var str = new System.Web.Script.Serialization.JavaScriptSerializer();

   TextBox1.Text =str.Serialize(u);

-------------js反序列化;

 success: function (result) {

                    var json = JSON.decode(result.d);

                    alert(json.Name);

--------------------當webservice出現方法重載時;

 [WebMethod( MessageName="guo")]在上面添加這個,一味着此方法的名字變爲了guo,客戶端只要調用guo就好了;

----------

 

------------------js調用後臺方法;

function Button1_onclick() {

    var a = " <% =getstr()%>";

    alert(a);

}

-------------------------------sql事務現成的案例:

 StringBuilder strSql = new StringBuilder();

            strSql.Append("begin transaction");

            strSql.Append(" DECLARE @inwages  decimal SET @inwages=0.0 ");

            strSql.Append(" DECLARE @outwages decimal set @outwages=0.0");

            strSql.Append(" select @inwages=sum(Wages)from GroupWages where IdCard=@idcard");

            strSql.Append(" SELECT @outwages=sum(AllWages) FROM PayWages WHERE IdCard=@idcard");

            strSql.Append(" SELECT @inwages-@outwages");

            strSql.Append(" IF @@error=0 commit transaction else rollback transaction ");

            SqlParameter[] parameters ={

             new SqlParameter("@idCard",idCard)

           };

------------------------------返回本月的第一天

txtBeginTime.Text = DateTime.Today.AddDays(-DateTime.Today.Day + 1).ToString("yyyy-MM-dd");

-----------------用戶自定義控件

用戶控件調用父頁面的方法:

 

 

//得到父頁面

Page p = this.Parent.Page;

Type pageType = p.GetType();

//父頁面的方法名

  //System.Reflection:要添加此命名空間;

MethodInfo mi = pageType.GetMethod("Loading");

//執行

mi.Invoke(p, new object[] { "參數1","參數2" });

用戶控件與用戶控件之間調用:

 

//得到父頁面

Page p = this.Parent.Page;

//得到父頁面的子控件

UserControl uc = p.FindControl("tj_ReceiptList2") as UserControl;

Type pageType = uc.GetType();

//父類方法名

MethodInfo mi = pageType.GetMethod("Loading");

//參數

mi.Invoke(uc, new object[] { "參數1", "參數2" });

 

 

用戶控件與用戶控件之間設置屬性:

 

 

//得到父頁面

Page p = this.Parent.Page;

//得到父頁面的子控件

UserControl uc = p.FindControl("aabb1") as UserControl;

Type pageType = uc.GetType();

//父類方法名

PropertyInfo mi = pageType.GetProperty("屬性名稱");

 

//mi.Invoke(uc, new object[] {});

mi.SetValue(uc,屬性值,null);

--------------------------------------------身份驗證登錄;(這兩種形式均可以;)

  System.Web.Security.FormsAuthentication.SetAuthCookie("a", false);

//System.Web.Security.FormsAuthentication.RedirectFromLoginPage("a",false);

 

System.Web.Security.FormsAuthentication.SignOut();

 

User.Identity.IsAuthenticated

 

--------------------------------------------mysql案例:

   MySqlConnection cn = new MySqlConnection("data source=localhost;initial catalog=gzf;uid=root;pwd=sa;persist security info=True;");

           // "server=localhost;user id=root;password=;database=guestbook"

            //MySqlConnection cn = new MySqlConnection("server=localhost;user id=root;password=sa;database=gzf");

            MySqlDataAdapter da = new MySqlDataAdapter(" select * from users", cn);

            DataSet ds = new DataSet();

            da.Fill(ds);

            this.dataGridView1.DataSource =ds.Tables[0];

--------------------------------返回上一頁

ViewState["preurl"]= Request.UrlReferrer.ToString();

 Response.Redirect(ViewState["preurl"].ToString());

---------------------------------------------------------實體中的datetime類型的默認值不爲空,而是datetime.minvalue;(時間)

-------------------------sqlin拼接:

存儲過程當中:1.轉化,2,用exec進行拼接;在c#直接拼接不能用軟綁定;

-----------------------路徑轉換

  protected static string Transfer(string str)

    {

        string[] strs = str.Split('/');

        if (str != "" && strs[strs.Length - 1].Length >= 7)

        {

            return strs[strs.Length - 1].Substring(0, 7);//得到路徑下文件的名稱

        }

        else

            return strs[strs.Length - 1];

    }

    protected static string TransferPath(string str)

    {

 

        return ("." + str.Replace('~', '.'));//轉換成下載路徑

    }

---------------------------複製表()

 DataTable dt2 = new DataTable();

            dt2 = dt.Copy();

            dt2.Rows.Clear();

            dt2.ImportRow(dt.Rows[0]);//這是加入的是第一行

------------------------------------------------------------------序列化與反序列化

 JavaScriptSerializer Serializer = new JavaScriptSerializer();

       Dictionary<string,string> objs = Serializer.Deserialize<Dictionary<string,string>>("{a:'guo',b:'ze'}");

 

 

   //List<aa> s = new List<aa>();

        //s = JSONStringToList<aa>("[{name:'guo'},{name:'ze'}]");

        //TextBox1.Text = s[1].name

    }

    public static List<T> JSONStringToList<T>(string JsonStr)

    {

        JavaScriptSerializer Serializer = new JavaScriptSerializer();

        List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);

        return objs;

    }

 

 

 

    public static List<T> JSONStringToList<T>(string JsonStr)

    {

        JavaScriptSerializer Serializer = new JavaScriptSerializer();

        List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);

        return objs;

    }

--------------------緩存依賴

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class Default4 : System.Web.UI.Page

{

    /// <summary>

    /// 獲取當前應用程序指定CacheKey的Cache對象值

    /// </summary>

    /// <param name="CacheKey">索引鍵值</param>

    /// <returns>返回緩存對象</returns>

    public static object GetCache(string CacheKey)

    {   

        System.Web.Caching.Cache objCache = HttpRuntime.Cache;   

        return objCache[CacheKey];

    }

 

 

    /// <summary>

    /// 設置以緩存依賴的方式緩存數據

    /// </summary>

    /// <param name="CacheKey">索引鍵值</param>

    /// <param name="objObject">緩存對象</param>

    /// <param name="cacheDepen">依賴對象</param>

    public static void SetCache(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep)

    {   

        System.Web.Caching.Cache objCache = HttpRuntime.Cache;   

        objCache.Insert(       

            CacheKey,       

            objObject,       

            dep,       

            System.Web.Caching.Cache.NoAbsoluteExpiration, //從不過時       

            System.Web.Caching.Cache.NoSlidingExpiration, //禁用可調過時       

            System.Web.Caching.CacheItemPriority.Default,       

            null);

    }

    protected void Page_Load(object sender, EventArgs e)

    {

        string CacheKey = "cachetest";

        object objModel = GetCache(CacheKey);

        //從緩存中獲取   

 

SELECT * FROM QualityCheck WHERE len(replace(Ensure,' ',''))>0        if (objModel == null) //緩存裏沒有   

        {       

            objModel = DateTime.Now;//把當前時間進行緩存        

            if (objModel != null)       

            {           

                //依賴 C:\\test.txt 文件的變化來更新緩存           

                System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency("C:\\test.txt");           

                SetCache(CacheKey, objModel, dep);//寫入緩存       

            }   

        }   

        Label1.Text = objModel.ToString();

    }

}

 

-----------------------判斷字段是否有值且不爲空;

 

SELECT * FROM QualityCheck WHERE len(replace(Ensure,' ',''))>0

---------------------------------------------------------------------------------------------------------js總結

1.  ---------------

-var aa = new Array();

            aa.push(1);

            alert(aa[0]);

var aa=[];也表示一個數組;

--------------------------

  var a = "sdfsfs";

            if (typeof (a) == "string")

                alert("shfidfodsf");

            else if (typeof (a) == "undefined")

                alert("未定義");

-----------------經過構造函數屬性來判斷類型;分割字符串

  var gg = "gu,oze,ng";

            var aa = gg.split(",");

            if(aa.constructor==Array)

                alert(aa[2]);

-------------------歸併字符串;

 var aa = new Array(1, 2, 3, 4);

            var b = aa.join("-");

            alert(b);

--------------------------

  $(document.body).css("background-color","Red");

---------------------:切記沒有分號,px後面,不然無效果;

  $("li").each(function () {

                $(this).css("background-color", "green");

                $(this).css("font-size","20px");

            });

--------------

 $("li:eq(3)").css("background-color", "red");匹配第四個li;

------------

 $("li:contains('b')").css("background-color",
"red");內容含有b的標籤;

---------------

 //$("ul").css("background-color","red");

            //$("ul").attr("style", "background-color:red; font-size:20px;");

            //$("ul").attr({ style: "background-color:red;",style: "background-color:red;"});

            $("ul").attr("class", "lii");

            $("ul").removeAttr("class");

-------------------------

$("p").addClass("selected highlight");

------------------得到索引:

.index();從0開始,返回一個數字;

-----------有的話,刪除,沒有的話添加;

  $("ul").click(function () {

                $(this).toggleClass("lii");

            });

--------------not:除此以外的;

  $("li").not($("li:last")).css("background-color", "red");

-------------2,3只選擇第三個,2,4只選擇第三和第四個,索引從0開始;當slice(2),表示從第三個到最後一個;

  $("li").slice(2,3).css("background-color", "red");

---------------------lt:前四個;

      $("li:gt(4)").css("background-color", "red");

-------全部的li;

   $("ul").children().css("background-color", "red");

--------class爲dd的類;

  $("ul").children(".dd").css("background-color", "red");

-------------全部的同級元素;

 $("#f").nextAll().css("background-color", "red");

-----------挨着的第一個同級元素;

 $("#f").next().css("background-color", "red");

-----------同級直到table標記之間的同級標記,不包括table;

 $("#f").nextUntil("table").css("background-color", "red");

-------------找到全部父級的標記;

   $("#nei").parents().css("background-color","red");

-------------應該只有上一級;

  $("#nei").parent().css("background-color","red");

-------------

siblings:除此以外的所同級元素;

---------至關於累加;

 $("#nei").add("table").add("#f").css("background-color","red");

-----------並把本身也加上;

$("div").find("p").andSelf().addClass("border");

--------------將全部元素添加到b標籤中;

   $("#nei").contents().wrap("<b/>");

-------------在p標籤的前面添加標記;append是後面;

$("p").prepend("<b>Hello</b>");

--------------.after,.before,insertafter,insertbefore;

------------將元素包含到另外一元素中;

$("p").wrap(document.getElementById('content'));

------------

將全部匹配的元素用單個元素包裹起來時使用wrapall();

---------------------------:在p的內部添加b;(將b的內容用b抱起來)

$("p").wrapInner("<b></b>");

-----------變換標記;

  $("p").click(function () {

                $(this).replaceWith("<img src='../img/_8-1.png'></img>");

-----------

            });

---------------------複製一份添加到標記中

$("b").clone().prependTo("p");

---------------------

將全部段落的字體顏色設爲紅色而且背景爲藍色。

 

jQuery 代碼:

$("p").css({ color: "#ff0011", background: "blue" });描述:

若是屬性名包含 "-"的話,必須使用引號:

jQuery 代碼:

$("p").css({ "margin-left": "10px", "background-color": "blue" });

-----------------------無論怎麼樣:鍵值都加雙引號;

$("#f").css({"color":"red","background":"blue"});

----------------------------------------------------------offset相對document的位置;

-----------設定移量;

  $("#xuan").offset({top:200,left:400});

-------------獲得相對位置

   var a = $("#xuan").offset();

            alert(a.left+"----"+a.top);

--------------------------------------------------------------position(),相對於父元素的偏移量;用法和offset同樣;

------blur():失去焦點觸發的事件;

-----change()事件:當內容改變且失去焦點時觸發;

-------------滾動條滾動

  $(window).scroll(function () {

                setTimeout();

               8

            });

-----------序列化操做:

   var a = $.parseJSON('{ "name": "guozeng" }');

            alert(a.name);

---------------------

------------------------textbox下拉框案例

  $(function () {

            $("#Text1").focus(function () {

                //$("#gg").attr("display","block");

                $("#gg").css("display", "block");

                $("#gg").offset({ top: $("#Text1").offset().top + $("#Text1").height() + 5, left: $("#Text1").offset().left });

            });

            $("li").click(function () {

                $("#Text1").val($(this).text());

                $("#gg").css("display", "none");

            });

        })

-------------------pannel案例:

 $(function () {

            $("img[alt='a']").click(function () {

                if ($(this).attr("src") == "../img/_8-1.png") {

                    $(this).attr("src", "../img/_8-2.png")

                    $("#gg").slideUp(500);

                }

                else {

                    $(this).attr("src", "../img/_8-1.png")

                    $("#gg").slideDown(500);

                }

            });

        })

------------------------------------------------------------------------------------------------------------------

1.new 父類方法:至關於複製了父類的方法,經過比對,不是重寫,因此沒有記錄到方法表的重寫表上。當父類引用指向子類實例時,調用該方法先去重寫表上找,若是沒找到,說明沒被重寫,因此繼續調用父類的方法;

2.繼承,其實是:先將父類複製一份分配內存,在和子類比對,將重寫的方法寫在loader heap的方法表上,當父類指向子類實例,先檢查方法表是否存在重寫方法,沒有的話,繼續調用父

類的。

3,棧:從高位到低位,控件有限,堆,從低位到高位,回收時,不管棧仍是堆,都從低位開始回收,全部就有的先進先出,先進後出之分;

4.進程棧,託管堆:gc堆,存儲屬性,loader heap:存儲方法表、靜態變量;生命週期:appdomain結束(應用程序域結束),當>85K時,存在loh上(large object heap)

5.類的靜態放在loader heap上,先於實例建立。屬性,不管引用仍是值都建立在堆上。方法裏的值建立在進程棧上。值類型中的引用對象的建立,還保持原來同樣,引用在棧,建立在堆上。

-----------------------------------------------

1:無論是重寫仍是覆蓋都不會影響父類自身的功能(廢話,確定的嘛,除非代碼被改)。

 

2:當用子類建立父類的時候,如 C1 c3 = new C2(),重寫會改變父類的功能,即調用子類的功能;而覆蓋不會,仍然調用父類功能。

 

3:虛方法、實方法均可以被覆蓋(new),抽象方法,接口 不能夠。

 

4:抽象方法,接口,標記爲virtual的方法能夠被重寫(override),實方法不能夠。

 

5:重寫使用的頻率比較高,實現多態;覆蓋用的頻率比較低,用於對之前沒法修改的類進行繼承的時候。

------------------------------------------soap序列化;

class Program

    {

        static void Main(string[] args)

        {

            //與二進制同樣

            Company com = new Company();

            com.CompanyName = "軟件開發公司";

            com.CompanyID = "1234";

            com.Office = "瀋陽";

            XmlTypeMapping map = (new SoapReflectionImporter().ImportTypeMapping(typeof(Company)));

            XmlTextWriter writer = new XmlTextWriter(@"C:\Users\dell\Desktop\123\aa.soap",Encoding.UTF8);

            writer.Formatting = Formatting.Indented;

            XmlSerializer xs = new XmlSerializer(map);

            writer.WriteStartElement("公司信息");

            xs.Serialize(writer, com);

            writer.WriteEndElement();

            writer.Close();

 

           

            XmlTextReader reader = new XmlTextReader(@"C:\Users\dell\Desktop\123\aa.soap");

            reader.ReadStartElement();

            Company ccom;

            ccom =(Company)xs.Deserialize(reader);

            reader.ReadEndElement();

            reader.Close();

            Console.WriteLine(ccom.ToString());

            Console.Read();

        }

    }

}

------------------

using System.Xml.Serialization;

namespace Soap協議

{

   public  class Company//必須是共有的;

    {

        [SoapAttribute(AttributeName="名稱")]

        public string CompanyName;

        [SoapElement]//默認名稱

        public string Office;

        [SoapIgnore]

        public string CompanyID;

        public override string ToString()

        {

            string m;

            m = "公司名稱:" + CompanyName + "\n";

            m += "公司地址:" + Office + "\n";

            m += "公司編號:" + CompanyID;

            return m;

        }

 

    }

}

------------------------------xml序列化

{

    class Program

    {

        static void Main(string[] args)

        {

            //條件:對象必須執行一次不帶殘的構造函數且必須共有的

            Meetion m = new Meetion("ATA");

            Meetion mm;

            m.roomNum = 505;

            m.invitees = new string[] {"smith","john" };

            XmlSerializer xs = new XmlSerializer(typeof(Meetion));

            StreamWriter sw = new StreamWriter(@"C:\Users\dell\Desktop\123\xml.txt");

            xs.Serialize(sw,m);

            sw.Close();

            StreamReader sr = new StreamReader(@"C:\Users\dell\Desktop\123\xml.txt");

            mm=(Meetion)xs.Deserialize(sr);

            Console.WriteLine(mm.roomNum);

        }

    }

    [XmlRoot(ElementName="會議")]

   public  class Meetion

    {

        private string title;

        [XmlAttribute(AttributeName="房間號")]

        public int roomNum;

        [XmlIgnore]

        public string[] invitees;

        public Meetion()

        {

 

        }

        public Meetion(string t)

        {

            title = t;

        }

    }

}

---------------------------二進制序列化:

using System.Runtime.Serialization.Formatters.Binary;//二進制序列化命名空間

using System.Collections;

using System.IO;

namespace 二進制序列化

{

    class Program

    {

        static void Serialize()

        {

            Hashtable t = new Hashtable();

            //反序列化進行自動排序int升序,字符串降序;

            t.Add(1, "瀋陽");

            t.Add(4, "撫順");

            t.Add(3, "北京");

            BinaryFormatter f = new BinaryFormatter();

            FileStream fs = new FileStream(@"C:\Users\dell\Desktop\123\as.txt", FileMode.Create);

            f.Serialize(fs, t);

            fs.Close();

        }

        /// <summary>

        /// 反序列化

        /// </summary>

        static void DeSerialize()

        {

            Hashtable ht = null;

            BinaryFormatter f = new BinaryFormatter();

            FileStream fs = new FileStream(@"C:\Users\dell\Desktop\123\as.txt", FileMode.Open);

            ht=(Hashtable)f.Deserialize(fs);

            foreach( DictionaryEntry item in ht)

            {

                Console.WriteLine( item.Key.ToString()+item.Value);

            }

           

        }

        static void Main(string[] args)

        {

            Serialize();

            DeSerialize();

            Console.Read();

        }

    }

}

---------------------------------------------打印楊輝三角

  //打印楊輝三角

        static void print(int n)

        {

            int mm = 0;

            Queue<int> q = new Queue<int>();

            Console.Write(space(n));//輸出空格

            for (int i = 1; i <= n; i++)

            {

                q.Enqueue(1);

                for (int j = 1; j < i; j++)

                {

                    mm = q.Dequeue();

                    Console.Write(mm + "-");//依次輸出每行數字

                    q.Enqueue(mm + q.Peek());

                }

                Console.Write(q.Peek());//輸出每行末尾數字  1

                Console.WriteLine();//開始打印下一行

                Console.Write(space(n - i));//輸出下一行空格

            }

            Console.Read();

        }

 

---------------------------------------------線程:

using System.Threading;

namespace Thread類

{

    class Program

    {

        //static void Main(string[] args)

        //{

        //    //幫助器委託不帶參數

        //    ThreadStart ts = new ThreadStart(DoWork)

        //    for (int i = 1; i <= 3; i++)

        //    {

        //        Thread t = new Thread(ts);

        //        t.Name = "線程"+i.ToString() ;

        //        t.Start();

        //    }

        //    Console.Read();

        //}

        //static void DoWork()

        //{

        //    for (int i = 0; i <= 9; i++)  

        //    {

        //        //不給名字的話,默認爲空;

        //        Console.WriteLine(Thread.CurrentThread.Name+"--"+i.ToString());

        //        Thread.Sleep(10);

        //    }

        //}

        //帶參數

        static void Main(string[] args)

        {

            //幫助器委託帶參數

            ParameterizedThreadStart ts = new ParameterizedThreadStart(DoWork);

            for (int i = 1; i <= 3; i++)

            {

                Thread t = new Thread(ts);

                t.Name = "線程" + i.ToString();

                t.Start(5);//在這裏指定參數(隱士轉換)

            }

            Console.Read();

        }

        static void DoWork(object obj)

        {

            for (int i = 1; i <=(int)obj; i++)

            {

                //不給名字的話,默認爲空;

                Console.WriteLine(Thread.CurrentThread.Name + "--" + i.ToString());

                Thread.Sleep(10);

            }

        }

    }

}

-------------------------------異步:

  class Program

    {

        public delegate int MathDelegate(int x, int y);

        static void Main(string[] args)

        {

           //IAsyncResult

           //異步編程必定要建立委託

            int a = Convert.ToInt32(Console.ReadLine());

            int b = Convert.ToInt32(Console.ReadLine());

            Class1 c1 = new Class1();

            MathDelegate md=new MathDelegate(c1.add);

            IAsyncResult r = md.BeginInvoke(a, b, null, null);

            while (!r.IsCompleted)

            {

                Console.WriteLine("我正在等結果,正在異步操做");

                Console.ReadLine();

            }

            int sum = md.EndInvoke(r);

            Console.WriteLine(su:m);

            Console.ReadLine();

        }

    }

 class Class1

    {

        public int add(int x, int y)

        {

            Thread.Sleep(5000);

            return x+y;

        }

    }

}

--------------------------------回調函數:

  delegate int FDeletate(int n);

        static FDeletate f;

        static void Main(string[] args)

        {

            f = new FDeletate(Fibonacci);

            AsyncCallback callback = new AsyncCallback(Display);//回調委託

            int n = Convert.ToInt32(Console.ReadLine());

            f.BeginInvoke(n, callback,"ggds");

            Console.ReadLine();

        }

        static int Fibonacci(int n)

        {

            if (n <= 1)

            {

                return 0;

            }

            else if (n == 1 || n == 2)

            {

                return n;

            }

            else

                return Fibonacci(n - 1) + Fibonacci(n - 2);

        }

        static void Display(IAsyncResult r)

        {

            int result = f.EndInvoke(r);

            Console.WriteLine("第"+r.AsyncState+"項值是"+result);

            Console.Read();

        }

----------------

Thread類有幾個相當重要的方法,描述以下:

Start():啓動線程;

Sleep(int):靜態方法,暫停當前線程指定的毫秒數;

Abort():一般使用該方法來終止一個線程;

Suspend():該方法並不終止未完成的線程,它僅僅掛起線程,之後還可恢復;

Resume():恢復被Suspend()方法掛起的線程的執行;

------只要是聚合函數就能夠用case when;group by 後面能夠加t-sql函數;

SELECT count(CASE WHEN CContent>4 THEN NULL ELSE 1 END) FROM DailyCheckRecord GROUP BY datepart(year,CDate)

--------------------------

select count(0):查詢結果爲1;

----------------------------------------(1):

 [ServiceContract(Name = "name_IUser", Namespace ="http://localhost:3232/wpf/aa")]

-------------------------------------------(2)

  [OperationContract(Name = "name_GetName", Action = "http://localhost:3232/wpf/aa/ServiceContract/GetName")]

--------------------------------(3)

using System.Runtime.Serialization;//datacontract;由此而來;須要添加引用的

--------------------李氏替換;不會剖出異常;

 //[KnownType(typeof(DataItem.SonDataUser))];(體現的是一種多態行處理)

------------------------(4)

  //isrequired:是否必須初始化;order;序列化時順序;

  [DataMember(Name="name_Name",IsRequired=false,Order=0)]

----------------------------------------------------------

object.Equals("0001/1/1 0:00:00", DateTime.MinValue.ToString()

 

 

-----------------------------------------------------------------------

property與attribute的區別:

property:有getset;button按鈕的寬度和高度;

attribute:好比:[serializable]

 

---------------------------------------------------------調用web服務生成成一步操做:必須這樣:(異步調用)

 protected void Button1_Click(object sender, EventArgs e)

    {

        ServiceReference1.WebServiceSoapClient a = new ServiceReference1.WebServiceSoapClient();

        a.HellowAsync(new ServiceReference1.HellowRequest(new ServiceReference1.HellowRequestBody(1)));

        a.HellowCompleted += new EventHandler<ServiceReference1.HellowCompletedEventArgs>(a_HellowCompleted);

    }

    public void a_HellowCompleted(object sender, ServiceReference1.HellowCompletedEventArgs e)

    {

        TextBox1.Text ="sff";

    }

------------------同步調用:

   ServiceReference1.WebServiceSoapClient a = new ServiceReference1.WebServiceSoapClient();

            //ServiceReference1.HellowResponse aa = a.Hellow(new ServiceReference1.HellowRequest(new ServiceReference1.HellowRequestBody(2)));

//MessageBox.Show(aa.Body.HellowResult.ToString());

------------------------------------------------------------------------

   if ($("#RadioButton1").attr("checked") ==true) {

                alert("郭澤峯呢個");

            }

------------------------jquery獲取dropdownlist的值;

 alert($("#dropProperty").find('option').filter(':selected').text());

var chec kText=$("#select_id").find("option:selected").text();  //獲取Select選擇的Text

-----------

  if ($("#RadioButton1").attr("checked") == true) {

                isBid = "是";

            }

------------------------js截取字符串;

 var param = hrefStr.substring(hrefStr.indexOf('?') + 1, hrefStr.length);

-------------

 var aa = $("a[href='/AjaxPaging/UpdataModel/" + hdnId + "']").parent().parent().find("td");

                        $(aa).slice(0, 1).text(name);

------------------------進程的Process的命名空間(using System.Diagnostics;)意思是診斷的意思;

 

   var ff = new Function("p1", "alert(p1)");

            ff(2);

---------------------------

  for(var a in arr)

            {

            alert(a);

            }

--------------w3c標準事件;(Ie不支持,其它支持)(注意兩個地方不同;)

 document.addEventListener("click", f1);

-------------ie;

  document.attachEvent("onclick",f1);

------------

window.event.clientX,clientY;鼠標在文檔的位置;

 

window.event.screenX,screenY;鼠標在瀏覽器的位置;

window.event.offsetX,offsetY;相對於事件源的位置;

window.event.returnValue=false;取消默認行爲;如提交按鈕不會提交;

----------------取消事件冒泡:

window.event.cancelBubble=true;

-----------動態建立:

  window.onload = function () {

            var btn = document.createElement("input");

            btn.name = "guo";

            btn.type = "button";

            btn.onclick = function () {

                alert("我去你大爺");

            };

            btn.value = "動態建立";

            var dv = document.getElementById("mm");

            dv.appendChild(btn);

        };

------------document.getelementbyid("").style.background="";

------------

onload與onready的區別:

onload,等documnet和css,js外部文件加載完以後才執行;只能註冊一次;

ready:只等document加載完畢以後才執行;可註冊多此;能夠提升響應速度;

----------

map:對數組遍歷;

each:對字典的遍歷;

---------------------

  //            $.each(person, function (key, value) {

            //                alert(key+"--"+value);

          > //            }, null);

            $.each(person, function () {alert(this) });//this,指的是值,由於咱們更對值感興趣;

=--------------\.next("div"):緊鄰的第一個;若是沒挨着;放回空;

-----。end(),方法返回上一次被破壞的包裝集,好比:$("#id").nextall().end(),指的是$("#id")

--

 $("#id").next().andSelf()//報錯本身和挨着的;

------去掉第一行:

$("#id tr:not(:first)");去掉第一行;

$("#id tr:not(:first):not(:last):even");各行設置;

-----------------全選;

 $("#checkall").click(function () {

            $(":checkbox[id*=checkbox]").attr("checked", $(this).attr("checked"));

        });

---------------------------05594054   0371

---動態建立子元素;

var a=$("<a  href='sdf'></a>")

a.css();

a.click();

$().append(a);

----------------remove:會移除對象的事件,但不會移除對象的樣式;

appendto();就至關於剪切粘貼;

----------$("#id").unbind();移除全部的事件;

.one("click",function(){});註冊一次性事件,用完後隨即unbind();若是沒有參數,就卸載全部的事件;

--------------------------------------------

  $("#Button1").bind("click", function () {

                alert(1);

            });

            $("#Button1").unbind("click");

-----------------------------------------------切換事件;第一次點擊顯示1,第二次顯示2;

  $("#Button1").toggle(function () { alert(1)}, function () { alert(2) });

--------------事件參數能夠防止事件冒泡;

$("#id").click(function(e){

  alert("郭");

  e.stopPropagetion();

});

這樣在id以外的標籤事件就不會觸發;

$("#id").click(function(e){

  alert("郭");

  e.preventDefault();//取消控件的默認行爲;與return false;不一樣的是,後續代碼繼續執行;好比取消鏈接的跳轉功能;

  alert("則");

});

-------------------

$(document).mousemove(function(e){

 

  $("#di").text(e.pageX+"=="+e.pageY);//獲取文檔的座標;

});

----------

$(document).mousemove(function(e){

 

  $("#di").css({"left":e.pageX,"top":e.pageY});//獲取文檔的座標;

 

});

 

-----------------擴展方法:

 $.extend({ "max": function (a, b) {

            if (a > b)

                return a;

        }, "min": function () {

            if (a < b)

                return a;

        }

------------------擴展實例方法:

  $.fn.extend({"checked":$(this).attr("checked","true")});

        $(function () {

           alert($.max(55,34));

 

       })

------調用: $("").checked();

----------------------------------

 $(window).width();

 

----------------------cookie:(須要引入cookie.js)

$.cookie("name",value,{expires=10})

----------------------------------frame;

   window.parent.afterEdit();

   var childWindow = $("#frameEdit")[0].contentWindow; //怎麼來拿frame標籤的一個window對象

                        childWindow.submitEditFrm();

 

---------------------數據綁定;gridview;

DataBinder.Eval(Container.DataItem,"Id")

 

--------------------------------------------------引用樣式表;css嵌套引用另外一個css文件;

@import url(cs1.css);

 

-------------------------

 <asp:UpdatePanel ID="UpdatePanel1" runat="server">

            <Triggers>

                <asp:PostBackTrigger ControlID="btnExport" />

            </Triggers>

------------------------------------------必須這樣:

 if (!object.Equals(reader["BidDate"], null) && !object.Equals(reader["BidDate"],DBNull.Value))

 if (!object.Equals(reader["BidDate"], null) &&reader["BidDate"].tostring()!="")

 

-------------------------------------------------------------------

1.new 父類方法:至關於複製了父類的方法,經過比對,不是重寫,因此沒有記錄到方法表的重寫表上。當父類引用指向子類實例時,調用該方法先去重寫表上找,若是沒找到,說明沒被重寫,因此繼續調用父類的方法;

2.繼承,其實是:先將父類複製一份分配內存,在和子類比對,將重寫的方法寫在loader heap的方法表上,當父類指向子類實例,先檢查方法表是否存在重寫方法,沒有的話,繼續調用父

類的。

3,棧:從高位到低位,控件有限,堆,從低位到高位,回收時,不管棧仍是堆,都從低位開始回收,全部就有的先進先出,先進後出之分;

4.進程棧,託管堆:gc堆,存儲屬性,loader heap:存儲方法表、靜態變量;生命週期:appdomain結束(應用程序域結束),當>85K時,存在loh上(large object heap)

5.類的靜態放在loader heap上,先於實例建立。屬性,不管引用仍是值都建立在堆上。方法裏的值建立在進程棧上。值類型中的引用對象的建立,還保持原來同樣,引用在棧,建立在堆上。

---------------

----------------導入excel:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using Excel;

namespace PM.Frame

{

    public class DataFromExcel

    {

        public static System.Data.DataTable DataTableforExcel(string strExcelFileName, string strSheetName)

        {

            System.Data.DataTable dt = new System.Data.DataTable();

            for (int i = 0; i < 19; i++)

            {

                dt.Columns.Add(new DataColumn());

            }

            Excel.Application excel = new Excel.Application();

            Excel.Workbook m_objBook = (Excel.Workbook)(excel.Workbooks.Add(strExcelFileName));

            Worksheet sheet = null;

            foreach (Worksheet wsheet in m_objBook.Worksheets)

            {

                if (wsheet.Name == strSheetName)

                {

                    sheet = wsheet;

                    break;

                }

            }

            if (sheet != null)

            {

                int row = 2;

                while (true)

                {

                    Range rName = sheet.Cells[row, 1] as Range;

                    if (rName.Text.ToString().Trim().Length == 0)

                    {

                        break;

                    }

                    DataRow dr = dt.NewRow();

                    for (int i = 0; i < 19; i++)

                    {

                        Range rContent = sheet.Cells[row, i + 1] as Range;

                        dr[i] = rContent.Text;

                    }

                    dt.Rows.Add(dr);

                    row += 1;

                }

            }

            excel.Quit();

            return dt;

        }

    }

}

 

//---======================================顯示網頁圖表icon

   <link rel="icon" href="a.ico"  type="image/ico" />

 

 

 

-------------------------------------------------------------------------------------

 //是否選中

 if ($("#CheckBox1").attr("checked"))

 {

    

 }

---------------------------------------------------------------pm導出excel:

 

 

 

//導出報表

    protected void btnExport_Click(object sender, EventArgs e)

    {

        //查詢條件得到數據集合;

        System.Data.DataTable ta = qm.GetAllTable(ViewState["queryModel"] as PCardBorrow);

 

        if (ta == null || ta.Rows.Count== 0)

        {

            Messabox.ShowError(this, "無記錄導出");

            return;

        }

        string name = "~/File/ExcelFile/證件借閱臺帳" + Session.SessionID + ".xls";

        string savePath = Server.MapPath(name);

        bool f = ExportExcel(name,ta, savePath);

        FileInfo DownloadFile = new FileInfo(savePath); //設置要下載的文件

        Response.Clear(); //清除緩衝區流中的全部內容輸出

        Response.ClearHeaders(); //清除緩衝區流中的全部頭

        Response.Buffer = false; //設置緩衝輸出爲false

        //設置輸出流的 HTTP MIME 類型爲application/octet-stream

        Response.ContentType = "application/octet-stream";//將 HTTP 頭添加到輸出流

        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("證件借閱臺帳.xls", System.Text.Encoding.UTF8));

        //Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());//將指定的文件直接寫入 HTTP 內容輸出流。

        //Response.WriteFile(DownloadFile.FullName);

        Response.WriteFile(savePath);

        Response.Flush(); //向客戶端發送當前全部緩衝的輸出

        File.Delete(savePath);//刪除文件

        Response.End(); //將當前全部緩衝的輸出發送到客戶端

    }

    //導出報表

    public bool ExportExcel(string reportName,System.Data.DataTable ta, string saveFileName)

    {

        if (ta == null)

        {

            return false;

        }

        bool fileSaved = false;

        Excel.Application m_objExcel = new Excel.Application();

        if (m_objExcel == null)

        {

            return false;

        }

        Excel.Workbooks m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;

        Excel.Workbook m_objBook = (Excel.Workbook)(m_objBooks.Add(Excel.XlWBATemplate.xlWBATWorksheet));

        Excel.Sheets m_objSheets = (Excel.Sheets)m_objBook.Worksheets;

        Excel._Worksheet m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));

        m_objSheet.Name = "Sheet1";

        Excel.Range range = null;

        long totalCount =ta.Rows.Count+ 2;

        long colnum = 11;//有12列;

        ((Excel.Range)m_objSheet.Cells).NumberFormatLocal = "@";//修改excel爲文本形式

        m_objSheet.get_Range(m_objSheet.Cells[1, 1], m_objSheet.Cells[totalCount, colnum]).Borders.LineStyle = XlLineStyle.xlContinuous;//設置全部表格線;

        ////第一行設置

        m_objExcel.get_Range(m_objSheet.Cells[1, 1], m_objSheet.Cells[1, colnum]).MergeCells = true;//合併單元格

        m_objExcel.get_Range(m_objSheet.Cells[1, 1], m_objSheet.Cells[1, colnum]).HorizontalAlignment = XlHAlign.xlHAlignCenter;//水平對齊方式

        m_objExcel.get_Range(m_objSheet.Cells[1, 1], m_objSheet.Cells[1, colnum]).VerticalAlignment = XlVAlign.xlVAlignCenter;//垂直對齊方式

        m_objExcel.get_Range(m_objSheet.Cells[1, 1], m_objSheet.Cells[1, colnum]).Font.Size = 14;

        m_objSheet.Cells[1, 1] = "證件借閱臺帳";

        m_objExcel.get_Range(m_objSheet.Cells[2, 1], m_objSheet.Cells[totalCount, colnum]).ColumnWidth = 20;//設置列的寬度;

        m_objExcel.get_Range(m_objSheet.Cells[2, 1], m_objSheet.Cells[2, colnum]).HorizontalAlignment = XlHAlign.xlHAlignCenter;//水平對齊方式

        m_objExcel.get_Range(m_objSheet.Cells[2, 1], m_objSheet.Cells[2, colnum]).VerticalAlignment = XlVAlign.xlVAlignCenter;//垂直對齊方式

       //設置格式

        for (int i = 1; i <= colnum; i++)

        {

            if (i <= 4 || i >= 10)

            {

                m_objExcel.get_Range(m_objSheet.Cells[2, i], m_objSheet.Cells[3, i]).MergeCells = true;//合併單元格

            }

        }

        m_objExcel.get_Range(m_objSheet.Cells[2, 5], m_objSheet.Cells[2, 7]).MergeCells = true;//合併單元格

        m_objExcel.get_Range(m_objSheet.Cells[2, 8], m_objSheet.Cells[2, 9]).MergeCells = true;//合併單元格

            //設置表頭:

        m_objSheet.Cells[2, 1] = "姓名";

        m_objSheet.Cells[2, 2] = "性別";

        m_objSheet.Cells[2, 3] = "證件類型";

        m_objSheet.Cells[2, 4] = "證件名稱";

        m_objSheet.Cells[2, 5] = "借閱形式";

        m_objSheet.Cells[2, 6] = "借閱部門或工程";

        m_objSheet.Cells[2, 7] = "借閱人";

        m_objSheet.Cells[2, 8] = "聯繫方式";

        m_objSheet.Cells[2, 9] = "借閱日期";

        m_objSheet.Cells[2, 10] = "是否歸還";

        m_objSheet.Cells[2, 11] = "歸還日期";

        //保存文件

        if (saveFileName != "")

        {

            try

            {

                m_objBook.Saved = true;

                m_objBook.SaveCopyAs(saveFileName);

                fileSaved = true;

            }

            catch (Exception ex)

            {

                fileSaved = false;

            }

        }

        else

        {

            fileSaved = false;

        }

        //釋放Excel對應的對象

        if (range != null)

        {

            System.Runtime.InteropServices.Marshal.ReleaseComObject(range);

            range = null;

        }

        if (m_objSheet != null)

        {

            System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet);

            m_objSheet = null;

        }

        if (m_objBook != null)

        {

            System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBook);

            m_objBook = null;

        }

        if (m_objBooks != null)

        {

            System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBooks);

            m_objBooks = null;

        }

        m_objExcel.Quit();

        if (m_objExcel != null)

        {

            System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel);

            m_objExcel = null;

        }

        GC.Collect();

        return fileSaved;

    }

}

--------------------------------存儲過程sql拼接

-- ================================================

-- Template generated from Template Explorer using:

-- Create Procedure (New Menu).SQL

--

-- Use the Specify Values for Template Parameters

-- command (Ctrl-Shift-M) to fill in the parameter

-- values below.

--

-- This block of comments will not be included in

-- the definition of the procedure.

-- ================================================

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Author:          <Author,,Name>

-- Create date: <Create Date,,>

-- Description: <Description,,>

-- =============================================

CREATE PROCEDURE [dbo].[PWageBT]

            (

          @PName varchar(100),

          @HBName varchar(50),

          @begintime datetime,

          @OverTime datetime

       )

AS

BEGIN

----查詢補貼金額技術

declare @workw money

declare @xxw money

declare @valw money

declare @xgdw money

--加班-工做日

select @workw=View_PWageBT.Wages  from View_PWageBT join PBuTieType on View_PWageBT.WageName=PBuTieType.Id

where PBuTieType.HBName='工做日'

--加班-休息日

select @xxw=View_PWageBT.Wages  from View_PWageBT join PBuTieType on View_PWageBT.WageName=PBuTieType.Id

where PBuTieType.HBName='休息日'

--加班-節假日

select @valw=View_PWageBT.Wages  from View_PWageBT join PBuTieType on View_PWageBT.WageName=PBuTieType.Id

where PBuTieType.HBName='節假日'

--下工地

select @xgdw=PWageSet.Wages  from PWageSet join PBuTieType on convert(int,PWageSet.WageName)=PBuTieType.Id

where PBuTieType.HBName='下工地' and PWageSet.WageType='補貼'

--統計加班數據

declare @str nvarchar(1000)

set @str=

'select *,case when HBName=''加班'' then WorkDays*@workw+RestDays*@xxw+ValDays*@valw else when HBName=''下工地'' then WorkDays*@xgdw end as AllMoney from View_PBTChild where 1=1 '

if(@PName<>'')

  set @str=@str+' and PName LIKE ''%'' + REPLACE(''' + @PName + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

if(@HBName<>'')

  set @str=@str+' and HBName LIKE ''%'' + REPLACE(''' + @HBName + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

if(@begintime<>'')

  set @str=@str+' and BDate>='''+@begintime+''''

if(@OverTime<>'')

   set @str=@str+' and BDate<='''+@OverTime+''''

END

GO

 

--------------------------------經典存儲過程(注意將變量用三個單引號或一個單引號都行,字符的話兩個單引號,若變量不爲字符串,必定要轉爲字符串在比較)好比;

set @str=

'select *,case when HBName=''加班'' then WorkDays*'+convert(varchar(10),@workw)+'+RestDays*'+convert(varchar(10),@xxw)+'+ValDays*'+convert(varchar(10),@valw)+' when HBName=''下工地'' then WorkDays*'+convert(varchar(10),@xgdw)+' end as AllMoney from View_PBTChild where 1=1 '

if(@PName<>'')

  set @str=@str+' and PName LIKE ''%'' + REPLACE(''' + @PName + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

if(@HBName<>'')

  set @str=@str+' and HBName LIKE ''%'' + REPLACE(''' + @HBName + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

if(@begintime<>'')

  set @str=@str+' and BDate>='''+convert(varchar(100),@begintime)+''''

if(@OverTime<>'')

   set @str=@str+' and BDate<='''+convert(varchar(100),@OverTime)+''''

 EXEC (@str)

END

-------------------------------------

---------------------sql順序:

select PerId,sum(WorkDays) as xdats from View_PBTChild group by PerId with rollup having 1=1 order by PerId

 

 

--------------------彙總案例

USE [SJCL1]

GO

/****** 對象:  StoredProcedure [dbo].[SZCHuiZong]    腳本日期: 07/07/2013 15:46:25 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

 

 

 

ALTER PROCEDURE [dbo].[SZCHuiZong]

@ZhongZhiRiQi   VARCHAR(20),

@QiShiRiQi   VARCHAR(20)

AS

set   nocount   on  

CREATE TABLE #ShouZhiCunMingXi(CLBH [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL,SL [float] NULL,JE [float] NULL,Lie [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL )

CREATE TABLE #T(CLBH [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL,SL [float] NULL,JE [float] NULL )

/*上月結存*/

 

/*初始化的*/

INSERT INTO #T(CLBH,SL,JE) SELECT XTBH, SUM(KCSL) AS SJSL, SUM(KCJE) AS SJJE FROM ZhangWuChuShiHua  GROUP BY XTBH

 

/*入庫的*/

INSERT INTO #T(CLBH,SL,JE) SELECT RKD_JH.CLXTBH, SUM(RKD_JH.SL) AS SJSL, SUM(RKD_JH.JE) AS SJJE

 FROM RKD_DJ inner join RKD_JH ON RKD_DJ.DJXTBH=RKD_JH.DJXTBH WHERE RKD_DJ.RQ <@QiShiRiQi GROUP BY RKD_JH.CLXTBH

 

/* 入庫退貨的*/

INSERT INTO #T(CLBH,SL,JE) SELECT RKTHD_JH.CLXTBH, -SUM(RKTHD_JH.SL) AS SJSL, -SUM(RKTHD_JH.JE) AS SJJE

 FROM RKTHD_DJ inner join RKTHD_JH ON RKTHD_DJ.DJXTBH=RKTHD_JH.DJXTBH WHERE RKTHD_DJ.RQ <@QiShiRiQi GROUP BY RKTHD_JH.CLXTBH

 

/*調撥入庫的*/

INSERT INTO #T(CLBH,SL,JE) SELECT DBRKD_JH.CLXTBH, SUM(DBRKD_JH.SL) AS SJSL, SUM(DBRKD_JH.JE) AS SJJE

FROM DBRKD_DJ inner join DBRKD_JH ON DBRKD_DJ.DJXTBH=DBRKD_JH.DJXTBH WHERE DBRKD_DJ.RQ <@QiShiRiQi GROUP BY DBRKD_JH.CLXTBH

 

/*調撥入庫退貨單*/

INSERT INTO #T(CLBH,SL,JE) SELECT DBRKTHD_JH.CLXTBH, -SUM(DBRKTHD_JH.SL) AS SJSL, -SUM(DBRKTHD_JH.JE) AS SJJE

 FROM DBRKTHD_DJ inner join DBRKTHD_JH ON DBRKTHD_DJ.DJXTBH=DBRKTHD_JH.DJXTBH WHERE DBRKTHD_DJ.RQ <@QiShiRiQi

 GROUP BY DBRKTHD_JH.CLXTBH

 

/*調撥出庫的*/

INSERT INTO #T(CLBH,SL,JE) SELECT DBCKD_JH.CLXTBH, -SUM(DBCKD_JH.SL) AS SJSL, -SUM(DBCKD_JH.JE) AS SJJE

 FROM DBCKD_DJ inner join DBCKD_JH ON DBCKD_DJ.DJXTBH=DBCKD_JH.DJXTBH WHERE DBCKD_DJ.RQ <@QiShiRiQi GROUP BY DBCKD_JH.CLXTBH

 

/*調撥出庫退貨單*/

INSERT INTO #T(CLBH,SL,JE) SELECT DBCKTHD_JH.CLXTBH, SUM(DBCKTHD_JH.SL) AS SJSL, SUM(DBCKTHD_JH.JE) AS SJJE

 FROM DBCKTHD_DJ inner join DBCKTHD_JH ON DBCKTHD_DJ.DJXTBH=DBCKTHD_JH.DJXTBH WHERE DBCKTHD_DJ.RQ <@QiShiRiQi

  GROUP BY DBCKTHD_JH.CLXTBH

 

/*發料的*/

INSERT INTO #T(CLBH,SL,JE) SELECT CKD_JH.CLXTBH,  -SUM(CKD_JH.SL) AS SJSL, -SUM(CKD_JH.JE) AS SJJE FROM CKD_DJ

 inner join CKD_JH ON CKD_DJ.DJXTBH=CKD_JH.CKD_DJ_DJXTBH WHERE CKD_DJ.RQ <@QiShiRiQi GROUP BY CKD_JH.CLXTBH

 

/*發料退回的*/

INSERT INTO #T(CLBH,SL,JE)  SELECT CKTHD_JH.CLXTBH, SUM(CKTHD_JH.SL) AS SJSL, SUM(CKTHD_JH.JE) AS SJJE

 FROM CKTHD_DJ inner join CKTHD_JH ON CKTHD_DJ.DJXTBH=CKTHD_JH.DJXTBH WHERE CKTHD_DJ.RQ <@QiShiRiQi GROUP BY CKTHD_JH.CLXTBH

 

/*盤點的量*/

INSERT INTO #T(CLBH,SL,JE) SELECT CLXTBH, SUM(CheckCount) AS SJSL, SUM(CheckJE) AS SJJE

 FROM StorageCheck WHERE CheckDate <@QiShiRiQi   GROUP BY CLXTBH

 

INSERT INTO #ShouZhiCunMingXi(CLBH,SL,JE,Lie) SELECT CLBH,SUM(SL) AS SL,SUM(JE) AS JE,'上月' AS LB FROM #T GROUP BY CLBH

 

DELETE FROM #T

 

/*本月月結存*/

 

/*初始化的*/

INSERT INTO #T(CLBH,SL,JE) SELECT XTBH, SUM(KCSL) AS SJSL, SUM(KCJE) AS SJJE FROM ZhangWuChuShiHua  GROUP BY XTBH

 

/*入庫的*/

INSERT INTO #T(CLBH,SL,JE) SELECT RKD_JH.CLXTBH,  SUM(RKD_JH.SL) AS SJSL, SUM(RKD_JH.JE) AS SJJE

 FROM RKD_DJ inner join RKD_JH ON RKD_DJ.DJXTBH=RKD_JH.DJXTBH WHERE RKD_DJ.RQ <= @ZhongZhiRiQi GROUP BY RKD_JH.CLXTBH

 

/* 入庫退貨的*/

INSERT INTO #T(CLBH,SL,JE) SELECT RKTHD_JH.CLXTBH, -SUM(RKTHD_JH.SL) AS SJSL, -SUM(RKTHD_JH.JE) AS SJJE

 FROM RKTHD_DJ inner join RKTHD_JH ON RKTHD_DJ.DJXTBH=RKTHD_JH.DJXTBH WHERE RKTHD_DJ.RQ <= @ZhongZhiRiQi GROUP BY RKTHD_JH.CLXTBH

 

/*調撥入庫的*/

INSERT INTO #T(CLBH,SL,JE) SELECT DBRKD_JH.CLXTBH, SUM(DBRKD_JH.SL) AS SJSL, SUM(DBRKD_JH.JE) AS SJJE

 FROM DBRKD_DJ inner join DBRKD_JH ON DBRKD_DJ.DJXTBH=DBRKD_JH.DJXTBH WHERE DBRKD_DJ.RQ <= @ZhongZhiRiQi

  GROUP BY DBRKD_JH.CLXTBH

 

/*調撥入庫退貨單*/

INSERT INTO #T(CLBH,SL,JE) SELECT DBRKTHD_JH.CLXTBH, -SUM(DBRKTHD_JH.SL) AS SJSL, -SUM(DBRKTHD_JH.JE) AS SJJE

FROM DBRKTHD_DJ inner join DBRKTHD_JH ON DBRKTHD_DJ.DJXTBH=DBRKTHD_JH.DJXTBH WHERE DBRKTHD_DJ.RQ <= @ZhongZhiRiQi

GROUP BY DBRKTHD_JH.CLXTBH

 

/*調撥出庫的*/

INSERT INTO #T(CLBH,SL,JE) SELECT DBCKD_JH.CLXTBH, -SUM(DBCKD_JH.SL) AS SJSL, -SUM(DBCKD_JH.JE) AS SJJE

 FROM DBCKD_DJ inner join DBCKD_JH ON DBCKD_DJ.DJXTBH=DBCKD_JH.DJXTBH WHERE DBCKD_DJ.RQ <= @ZhongZhiRiQi

  GROUP BY DBCKD_JH.CLXTBH

 

/*調撥出庫退貨單*/

INSERT INTO #T(CLBH,SL,JE) SELECT DBCKTHD_JH.CLXTBH, SUM(DBCKTHD_JH.SL) AS SJSL, SUM(DBCKTHD_JH.JE) AS SJJE

 FROM DBCKTHD_DJ inner join DBCKTHD_JH ON DBCKTHD_DJ.DJXTBH=DBCKTHD_JH.DJXTBH WHERE DBCKTHD_DJ.RQ <= @ZhongZhiRiQi

 GROUP BY DBCKTHD_JH.CLXTBH

 

/*發料的*/

INSERT INTO #T(CLBH,SL,JE) SELECT CKD_JH.CLXTBH, -SUM(CKD_JH.SL) AS SJSL, -SUM(CKD_JH.JE) AS SJJE

 FROM CKD_DJ inner join CKD_JH ON CKD_DJ.DJXTBH=CKD_JH.CKD_DJ_DJXTBH WHERE CKD_DJ.RQ <= @ZhongZhiRiQi

  GROUP BY CKD_JH.CLXTBH

 

/*發料退回的*/

INSERT INTO #T(CLBH,SL,JE)  SELECT CKTHD_JH.CLXTBH, SUM(CKTHD_JH.SL) AS SJSL, SUM(CKTHD_JH.JE) AS SJJE

FROM CKTHD_DJ inner join CKTHD_JH ON CKTHD_DJ.DJXTBH=CKTHD_JH.DJXTBH WHERE CKTHD_DJ.RQ <= @ZhongZhiRiQi

 GROUP BY CKTHD_JH.CLXTBH

 

/*盤點的量*/

INSERT INTO #T(CLBH,SL,JE) SELECT CLXTBH, SUM(CheckCount) AS SJSL, SUM(CheckJE) AS SJJE FROM StorageCheck

WHERE CheckDate <=@ZhongZhiRiQi   GROUP BY CLXTBH

 

INSERT INTO #ShouZhiCunMingXi(CLBH,SL,JE,Lie) SELECT CLBH,SUM(SL) AS SL,SUM(JE) AS JE,'本月' AS LB FROM #T GROUP BY CLBH

 

DELETE FROM #T

 

 

/*本月入庫*/

 

/*入庫的*/

INSERT INTO #T(CLBH,SL,JE) SELECT RKD_JH.CLXTBH, SUM(RKD_JH.SL) AS SJSL, SUM(RKD_JH.JE) AS SJJE

 FROM RKD_DJ inner join RKD_JH ON RKD_DJ.DJXTBH=RKD_JH.DJXTBH WHERE RKD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi

 GROUP BY RKD_JH.CLXTBH

 

/* 入庫退貨的*/

INSERT INTO #T(CLBH,SL,JE) SELECT RKTHD_JH.CLXTBH, -SUM(RKTHD_JH.SL) AS SJSL, -SUM(RKTHD_JH.JE) AS SJJE

FROM RKTHD_DJ inner join RKTHD_JH ON RKTHD_DJ.DJXTBH=RKTHD_JH.DJXTBH WHERE RKTHD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi

GROUP BY RKTHD_JH.CLXTBH

 

/*調撥入庫的*/

INSERT INTO #T(CLBH,SL,JE) SELECT DBRKD_JH.CLXTBH, SUM(DBRKD_JH.SL) AS SJSL, SUM(DBRKD_JH.JE) AS SJJE

FROM DBRKD_DJ inner join DBRKD_JH ON DBRKD_DJ.DJXTBH=DBRKD_JH.DJXTBH

 WHERE DBRKD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY DBRKD_JH.CLXTBH

 

/*調撥入庫退貨單*/

INSERT INTO #T(CLBH,SL,JE) SELECT DBRKTHD_JH.CLXTBH, -SUM(DBRKTHD_JH.SL) AS SJSL, -SUM(DBRKTHD_JH.JE) AS SJJE

 FROM DBRKTHD_DJ inner join DBRKTHD_JH ON DBRKTHD_DJ.DJXTBH=DBRKTHD_JH.DJXTBH WHERE DBRKTHD_DJ.RQ

  BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY DBRKTHD_JH.CLXTBH

 

INSERT INTO #ShouZhiCunMingXi(CLBH,SL,JE,Lie) SELECT CLBH,SUM(SL) AS SL,SUM(JE) AS JE,'入庫' AS LB FROM #T GROUP BY CLBH

 

DELETE FROM #T

 

/*本月出庫的*/

 

/*發料的*/

INSERT INTO #T(CLBH,SL,JE) SELECT CKD_JH.CLXTBH, SUM(CKD_JH.SL) AS SJSL, SUM(CKD_JH.JE) AS SJJE

 FROM CKD_DJ inner join CKD_JH ON CKD_DJ.DJXTBH=CKD_JH.CKD_DJ_DJXTBH

 WHERE CKD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY CKD_JH.CLXTBH

 

/*發料退回的*/

INSERT INTO #T(CLBH,SL,JE)  SELECT CKTHD_JH.CLXTBH, -SUM(CKTHD_JH.SL) AS SJSL, -SUM(CKTHD_JH.JE) AS SJJE

FROM CKTHD_DJ inner join CKTHD_JH ON CKTHD_DJ.DJXTBH=CKTHD_JH.DJXTBH

 WHERE CKTHD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY CKTHD_JH.CLXTBH

 

/*調撥出庫的*/

INSERT INTO #T(CLBH,SL,JE) SELECT DBCKD_JH.CLXTBH, SUM(DBCKD_JH.SL) AS SJSL, SUM(DBCKD_JH.JE) AS SJJE

 FROM DBCKD_DJ inner join DBCKD_JH ON DBCKD_DJ.DJXTBH=DBCKD_JH.DJXTBH

  WHERE DBCKD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY DBCKD_JH.CLXTBH

 

/*調撥出庫退貨單*/

INSERT INTO #T(CLBH,SL,JE) SELECT DBCKTHD_JH.CLXTBH, -SUM(DBCKTHD_JH.SL) AS SJSL, -SUM(DBCKTHD_JH.JE) AS SJJE

 FROM DBCKTHD_DJ inner join DBCKTHD_JH ON DBCKTHD_DJ.DJXTBH=DBCKTHD_JH.DJXTBH

  WHERE DBCKTHD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY DBCKTHD_JH.CLXTBH

 

INSERT INTO #ShouZhiCunMingXi(CLBH,SL,JE,Lie) SELECT CLBH,SUM(SL) AS SL,SUM(JE) AS JE,'出庫' AS LB FROM #T GROUP BY CLBH

 

DELETE FROM #T

 

 

--第一步:根據系統編號、列、單價分組求和

select CLBH,sum(SL) as SL,sum(JE) as JE,Lie

                            into #TempSZCMX

 from #ShouZhiCunMingXi group by Lie, CLBH  order by Lie,CLBH

 

 

 --第二步:列轉行,分組求和

SELECT YJ,EJ,

         MoJi=(CASE WHEN grouping(YJ) = 1 THEN '0' 

                            WHEN grouping(EJ) = 1 THEN [YJ]

                            WHEN grouping(MoJi) = 1 THEN [EJ] ELSE MoJi END),

sum(SYSL) SYSL,SUM(SYJE) SYJE,SUM(BYSL) BYSL,SUM(BYJE) BYJE,

SUM(CKSL) CKSL,SUM(CKJE) CKJE,SUM(RKSL) RKSL,SUM(RKJE) RKJE

into SysCl.##TempLastResults

from

(

select CaiLiaoXinxi_1.SJ AS YJ,CaiLiaoXinxi_1.BH AS EJ,CaiLiaoXinxi.BH AS MoJi,

sum(case Lie when '上月' then SL else 0 end) as 'SYSL',

                            sum(case Lie when '上月' then JE else 0 end) as 'SYJE',

                            sum(case Lie when '本月' then SL else 0 end) as 'BYSL',

                            sum(case Lie when '本月' then JE else 0 end) as 'BYJE',

                            sum(case Lie when '出庫' then SL else 0 end) as 'CKSL',

                            sum(case Lie when '出庫' then JE else 0 end) as 'CKJE',

                            sum(case Lie when '入庫' then SL else 0 end) as 'RKSL',

                            sum(case Lie when '入庫' then JE else 0 end) as 'RKJE'

                            from #TempSZCMX inner join CaiLiaoXinxi ON #TempSZCMX.CLBH =CaiLiaoXinxi.XTBH

                            INNER JOIN CaiLiaoXinxi  CaiLiaoXinxi_1 ON CaiLiaoXinxi.SJ=CaiLiaoXinxi_1.BH

                            GROUP BY CaiLiaoXinxi.BH ,CaiLiaoXinxi_1.BH,CaiLiaoXinxi_1.SJ ) as MingXi

                            group by YJ,EJ,MoJi with rollup

 

 

set   nocount   off

----------------------------彙總案例(材料)

ALTER PROCEDURE [dbo].[TeShuJiJia] 

@ZhongZhiRiQi   VARCHAR(20),

@QiShiRiQi   VARCHAR(20),

@LeiBie   VARCHAR(100),

@IsYD   bit

 AS

set   nocount   on  

CREATE TABLE #ShouZhiCunMingXi(CLBH [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL,DJ [float] NULL,

SL [float] NULL,JE [float] NULL,Lie [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL )

CREATE TABLE #T(CLBH [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL,DJ [float] NULL,SL [float] NULL,JE [float] NULL )

create table #lastResult(CLBH [varchar] (50) collate Chinese_PRC_CI_AS null,

                                                        SYSL [float] null,

                                                        SYJE [float] null,

                                                        BYSL [float] null,

                                                        BYJE [float] null,

                                                        CKSL [float] null,

                                                        CKJE [float] null,

                                                        RKSL [float] null,

                                                        RKJE [float] null)

create table #TempLastResults(YJ [varchar](50),EJ [varchar](50),MoJi [varchar](50),DJ [FLOAT] DEFAULT 0,

SYSL  [FLOAT] DEFAULT 0,SYJE  [FLOAT] DEFAULT 0,BYSL [FLOAT] DEFAULT 0,BYJE [FLOAT] DEFAULT 0,

CKSL [FLOAT] DEFAULT 0,CKJE [FLOAT] DEFAULT 0,RKSL [FLOAT] DEFAULT 0,RKJE [FLOAT] DEFAULT 0)

/*上月結存*/

 

 

if(@IsYD='true')

begin

/*含預點的入庫單*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT YDRKD_JH.CLXTBH, YDRKD_JH.DJ, SUM(YDRKD_JH.SL) AS SJSL, SUM(YDRKD_JH.JE) AS SJJE

 FROM YDRKD_DJ inner join YDRKD_JH ON YDRKD_DJ.DJXTBH=YDRKD_JH.DJXTBH

WHERE YDRKD_DJ.RQ <@QiShiRiQi GROUP BY YDRKD_JH.CLXTBH, YDRKD_JH.DJ

 

/*含預點的發料單*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT YDCKD_JH.CLXTBH, YDCKD_JH.KCDJ, -SUM(YDCKD_JH.SL) AS SJSL,

 -SUM(YDCKD_JH.JE) AS SJJE FROM YDCKD_DJ inner join YDCKD_JH ON YDCKD_DJ.DJXTBH=YDCKD_JH.CKD_DJ_DJXTBH

  WHERE YDCKD_DJ.RQ <@QiShiRiQi GROUP BY YDCKD_JH.CLXTBH, YDCKD_JH.KCDJ

 

end

 

/*初始化的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT XTBH, KCDJ, SUM(KCSL) AS SJSL, SUM(KCJE) AS SJJE FROM ZhangWuChuShiHua

  GROUP BY XTBH, KCDJ

 

/*入庫的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT RKD_JH.CLXTBH, RKD_JH.DJ, SUM(RKD_JH.SL) AS SJSL, SUM(RKD_JH.JE) AS SJJE

 FROM RKD_DJ inner join RKD_JH ON RKD_DJ.DJXTBH=RKD_JH.DJXTBH WHERE RKD_DJ.RQ <@QiShiRiQi GROUP BY RKD_JH.CLXTBH, RKD_JH.DJ

 

/* 入庫退貨的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT RKTHD_JH.CLXTBH, RKTHD_JH.DJ, -SUM(RKTHD_JH.SL) AS SJSL, -SUM(RKTHD_JH.JE) AS SJJE

FROM RKTHD_DJ inner join RKTHD_JH ON RKTHD_DJ.DJXTBH=RKTHD_JH.DJXTBH WHERE RKTHD_DJ.RQ <@QiShiRiQi

 GROUP BY RKTHD_JH.CLXTBH, RKTHD_JH.DJ

 

/*調撥入庫的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT DBRKD_JH.CLXTBH, DBRKD_JH.DJ, SUM(DBRKD_JH.SL) AS SJSL,

 SUM(DBRKD_JH.JE) AS SJJE FROM DBRKD_DJ inner join DBRKD_JH ON DBRKD_DJ.DJXTBH=DBRKD_JH.DJXTBH WHERE DBRKD_DJ.RQ <@QiShiRiQi

  GROUP BY DBRKD_JH.CLXTBH, DBRKD_JH.DJ

 

/*調撥入庫退貨單*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT DBRKTHD_JH.CLXTBH, DBRKTHD_JH.DJ, -SUM(DBRKTHD_JH.SL) AS SJSL,

 -SUM(DBRKTHD_JH.JE) AS SJJE FROM DBRKTHD_DJ inner join DBRKTHD_JH ON DBRKTHD_DJ.DJXTBH=DBRKTHD_JH.DJXTBH

 WHERE DBRKTHD_DJ.RQ <@QiShiRiQi GROUP BY DBRKTHD_JH.CLXTBH, DBRKTHD_JH.DJ

 

/*調撥出庫的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT DBCKD_JH.CLXTBH, DBCKD_JH.KCDJ, -SUM(DBCKD_JH.SL) AS SJSL,

 -SUM(DBCKD_JH.JE) AS SJJE FROM DBCKD_DJ inner join DBCKD_JH ON DBCKD_DJ.DJXTBH=DBCKD_JH.DJXTBH

  WHERE DBCKD_DJ.RQ <@QiShiRiQi GROUP BY DBCKD_JH.CLXTBH, DBCKD_JH.KCDJ

 

/*調撥出庫退貨單*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT DBCKTHD_JH.CLXTBH, DBCKTHD_JH.KCDJ, SUM(DBCKTHD_JH.SL) AS SJSL,

 SUM(DBCKTHD_JH.JE) AS SJJE FROM DBCKTHD_DJ inner join DBCKTHD_JH ON DBCKTHD_DJ.DJXTBH=DBCKTHD_JH.DJXTBH

  WHERE DBCKTHD_DJ.RQ <@QiShiRiQi GROUP BY DBCKTHD_JH.CLXTBH, DBCKTHD_JH.KCDJ

 

/*發料的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT CKD_JH.CLXTBH, CKD_JH.KCDJ, -SUM(CKD_JH.SL) AS SJSL,

 -SUM(CKD_JH.JE) AS SJJE FROM CKD_DJ inner join CKD_JH ON CKD_DJ.DJXTBH=CKD_JH.CKD_DJ_DJXTBH

  WHERE CKD_DJ.RQ <@QiShiRiQi GROUP BY CKD_JH.CLXTBH, CKD_JH.KCDJ

 

/*發料退回的*/

INSERT INTO #T(CLBH,DJ,SL,JE)  SELECT CKTHD_JH.CLXTBH, CKTHD_JH.KCDJ, SUM(CKTHD_JH.SL) AS SJSL,

 SUM(CKTHD_JH.JE) AS SJJE FROM CKTHD_DJ inner join CKTHD_JH ON CKTHD_DJ.DJXTBH=CKTHD_JH.DJXTBH

  WHERE CKTHD_DJ.RQ <@QiShiRiQi GROUP BY CKTHD_JH.CLXTBH, CKTHD_JH.KCDJ

 

/*盤點的量*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT CLXTBH, KCDJ, SUM(DifferenceCount) AS SJSL, SUM(DifferenceCount*KCDJ) AS SJJE

 FROM StorageCheck WHERE CheckDate <@QiShiRiQi   GROUP BY CLXTBH, KCDJ

 

INSERT INTO #ShouZhiCunMingXi(CLBH,DJ,SL,JE,Lie) SELECT CLBH,DJ,SUM(SL) AS SL,SUM(JE) AS JE,'上月' AS LB

 FROM #T GROUP BY CLBH,DJ

 

DELETE FROM #T

 

/*本月月結存*/

 

 

if(@IsYD='true')

begin

/*含預點的入庫單*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT YDRKD_JH.CLXTBH, YDRKD_JH.DJ, SUM(YDRKD_JH.SL) AS SJSL, SUM(YDRKD_JH.JE) AS SJJE

 FROM YDRKD_DJ inner join YDRKD_JH ON YDRKD_DJ.DJXTBH=YDRKD_JH.DJXTBH

  WHERE YDRKD_DJ.RQ <= @ZhongZhiRiQi  GROUP BY YDRKD_JH.CLXTBH, YDRKD_JH.DJ

 

/*含預點的發料單*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT YDCKD_JH.CLXTBH, YDCKD_JH.KCDJ, -SUM(YDCKD_JH.SL) AS SJSL,

 -SUM(YDCKD_JH.JE) AS SJJE FROM YDCKD_DJ inner join YDCKD_JH ON YDCKD_DJ.DJXTBH=YDCKD_JH.CKD_DJ_DJXTBH

  WHERE YDCKD_DJ.RQ <= @ZhongZhiRiQi  GROUP BY YDCKD_JH.CLXTBH, YDCKD_JH.KCDJ

 

end

 

 

/*初始化的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT XTBH, KCDJ, SUM(KCSL) AS SJSL, SUM(KCJE) AS SJJE

FROM ZhangWuChuShiHua  GROUP BY XTBH, KCDJ

 

/*入庫的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT RKD_JH.CLXTBH, RKD_JH.DJ, SUM(RKD_JH.SL) AS SJSL,

 SUM(RKD_JH.JE) AS SJJE FROM RKD_DJ inner join RKD_JH ON RKD_DJ.DJXTBH=RKD_JH.DJXTBH

  WHERE RKD_DJ.RQ <= @ZhongZhiRiQi GROUP BY RKD_JH.CLXTBH, RKD_JH.DJ

 

/* 入庫退貨的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT RKTHD_JH.CLXTBH, RKTHD_JH.DJ, -SUM(RKTHD_JH.SL) AS SJSL,

-SUM(RKTHD_JH.JE) AS SJJE FROM RKTHD_DJ inner join RKTHD_JH ON RKTHD_DJ.DJXTBH=RKTHD_JH.DJXTBH

WHERE RKTHD_DJ.RQ <= @ZhongZhiRiQi GROUP BY RKTHD_JH.CLXTBH, RKTHD_JH.DJ

 

/*調撥入庫的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT DBRKD_JH.CLXTBH, DBRKD_JH.DJ, SUM(DBRKD_JH.SL) AS SJSL,

SUM(DBRKD_JH.JE) AS SJJE FROM DBRKD_DJ inner join DBRKD_JH ON DBRKD_DJ.DJXTBH=DBRKD_JH.DJXTBH

WHERE DBRKD_DJ.RQ <= @ZhongZhiRiQi GROUP BY DBRKD_JH.CLXTBH, DBRKD_JH.DJ

 

/*調撥入庫退貨單*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT DBRKTHD_JH.CLXTBH, DBRKTHD_JH.DJ, -SUM(DBRKTHD_JH.SL) AS SJSL,

 -SUM(DBRKTHD_JH.JE) AS SJJE FROM DBRKTHD_DJ inner join DBRKTHD_JH ON DBRKTHD_DJ.DJXTBH=DBRKTHD_JH.DJXTBH

 WHERE DBRKTHD_DJ.RQ <= @ZhongZhiRiQi GROUP BY DBRKTHD_JH.CLXTBH, DBRKTHD_JH.DJ

 

/*調撥出庫的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT DBCKD_JH.CLXTBH, DBCKD_JH.KCDJ, -SUM(DBCKD_JH.SL) AS SJSL,

 -SUM(DBCKD_JH.JE) AS SJJE FROM DBCKD_DJ inner join DBCKD_JH ON DBCKD_DJ.DJXTBH=DBCKD_JH.DJXTBH

  WHERE DBCKD_DJ.RQ <= @ZhongZhiRiQi GROUP BY DBCKD_JH.CLXTBH, DBCKD_JH.KCDJ

 

/*調撥出庫退貨單*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT DBCKTHD_JH.CLXTBH, DBCKTHD_JH.KCDJ, SUM(DBCKTHD_JH.SL) AS SJSL,

 SUM(DBCKTHD_JH.JE) AS SJJE FROM DBCKTHD_DJ inner join DBCKTHD_JH ON DBCKTHD_DJ.DJXTBH=DBCKTHD_JH.DJXTBH

  WHERE DBCKTHD_DJ.RQ <= @ZhongZhiRiQi GROUP BY DBCKTHD_JH.CLXTBH, DBCKTHD_JH.KCDJ

 

/*發料的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT CKD_JH.CLXTBH, CKD_JH.KCDJ, -SUM(CKD_JH.SL) AS SJSL,

-SUM(CKD_JH.JE) AS SJJE FROM CKD_DJ inner join CKD_JH ON CKD_DJ.DJXTBH=CKD_JH.CKD_DJ_DJXTBH

WHERE CKD_DJ.RQ <= @ZhongZhiRiQi GROUP BY CKD_JH.CLXTBH, CKD_JH.KCDJ

 

/*發料退回的*/

INSERT INTO #T(CLBH,DJ,SL,JE)  SELECT CKTHD_JH.CLXTBH, CKTHD_JH.KCDJ, SUM(CKTHD_JH.SL) AS SJSL,

SUM(CKTHD_JH.JE) AS SJJE FROM CKTHD_DJ inner join CKTHD_JH ON CKTHD_DJ.DJXTBH=CKTHD_JH.DJXTBH

WHERE CKTHD_DJ.RQ <= @ZhongZhiRiQi GROUP BY CKTHD_JH.CLXTBH, CKTHD_JH.KCDJ

 

/*盤點的量*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT CLXTBH, KCDJ, SUM(DifferenceCount) AS SJSL, SUM(DifferenceCount*KCDJ) AS SJJE

 FROM StorageCheck WHERE CheckDate <=@ZhongZhiRiQi   GROUP BY CLXTBH, KCDJ

 

INSERT INTO #ShouZhiCunMingXi(CLBH,DJ,SL,JE,Lie) SELECT CLBH,DJ,SUM(SL) AS SL,SUM(JE) AS JE,'本月' AS LB

FROM #T GROUP BY CLBH,DJ

 

DELETE FROM #T

 

 

/*本月入庫*/

 

 

if(@IsYD='true')

begin

/*含預點的入庫單*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT YDRKD_JH.CLXTBH, YDRKD_JH.DJ, SUM(YDRKD_JH.SL) AS SJSL, SUM(YDRKD_JH.JE) AS SJJE

 FROM YDRKD_DJ inner join YDRKD_JH ON YDRKD_DJ.DJXTBH=YDRKD_JH.DJXTBH

  WHERE YDRKD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY YDRKD_JH.CLXTBH, YDRKD_JH.DJ

/*直進直出入庫*/

 INSERT INTO #T(CLBH,DJ,SL,JE) SELECT YDZJZC_JH.CLXTBH,YDZJZC_JH.CGDJ, sum(YDZJZC_JH.SL) as SJSL,sum(YDZJZC_JH.CGJE) as SJJE

FROM  YDRKD_DJ INNER JOIN YDZJZC_JH ON YDRKD_DJ.DJXTBH = YDZJZC_JH.DJXTBH WHERE YDRKD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY YDZJZC_JH.CLXTBH,YDZJZC_JH.CGDJ

 

 

end

 

/*入庫的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT RKD_JH.CLXTBH, RKD_JH.DJ, SUM(RKD_JH.SL) AS SJSL,

 SUM(RKD_JH.JE) AS SJJE FROM RKD_DJ inner join RKD_JH ON RKD_DJ.DJXTBH=RKD_JH.DJXTBH

  WHERE RKD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY RKD_JH.CLXTBH, RKD_JH.DJ

 

/* 入庫退貨的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT RKTHD_JH.CLXTBH, RKTHD_JH.DJ, -SUM(RKTHD_JH.SL) AS SJSL,

 -SUM(RKTHD_JH.JE) AS SJJE FROM RKTHD_DJ inner join RKTHD_JH ON RKTHD_DJ.DJXTBH=RKTHD_JH.DJXTBH

  WHERE RKTHD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY RKTHD_JH.CLXTBH, RKTHD_JH.DJ

 

/*調撥入庫的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT DBRKD_JH.CLXTBH, DBRKD_JH.DJ, SUM(DBRKD_JH.SL) AS SJSL,

SUM(DBRKD_JH.JE) AS SJJE FROM DBRKD_DJ inner join DBRKD_JH ON DBRKD_DJ.DJXTBH=DBRKD_JH.DJXTBH

 WHERE DBRKD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY DBRKD_JH.CLXTBH, DBRKD_JH.DJ

 

/*調撥入庫退貨單*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT DBRKTHD_JH.CLXTBH, DBRKTHD_JH.DJ, -SUM(DBRKTHD_JH.SL) AS SJSL,

 -SUM(DBRKTHD_JH.JE) AS SJJE FROM DBRKTHD_DJ inner join DBRKTHD_JH ON DBRKTHD_DJ.DJXTBH=DBRKTHD_JH.DJXTBH

  WHERE DBRKTHD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY DBRKTHD_JH.CLXTBH, DBRKTHD_JH.DJ

/*直進直出入庫*/

 INSERT INTO #T(CLBH,DJ,SL,JE) SELECT ZJZC_JH.CLXTBH,ZJZC_JH.CGDJ, sum(ZJZC_JH.SL) as SJSL,sum(ZJZC_JH.CGJE) as SJJE

FROM  ZJZC_DJ INNER JOIN ZJZC_JH ON ZJZC_DJ.DJXTBH = ZJZC_JH.DJXTBH WHERE ZJZC_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY ZJZC_JH.CLXTBH,ZJZC_JH.CGDJ

/*直進直出入庫退貨*/

 INSERT INTO #T(CLBH,DJ,SL,JE) SELECT ZJZCTH_JH.CLXTBH, ZJZCTH_JH.CGTHDJ,-sum(ZJZCTH_JH.SL) as SJSL,-sum(ZJZCTH_JH.CGTHJE) as SJJE

FROM  ZJZCTH_DJ INNER JOIN ZJZCTH_JH ON ZJZCTH_DJ.DJXTBH = ZJZCTH_JH.DJXTBH WHERE ZJZCTH_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY ZJZCTH_JH.CLXTBH,ZJZCTH_JH.CGTHDJ

 

INSERT INTO #ShouZhiCunMingXi(CLBH,DJ,SL,JE,Lie) SELECT CLBH,DJ,SUM(SL) AS SL,SUM(JE) AS JE,'入庫' AS LB

 FROM #T GROUP BY CLBH,DJ

 

DELETE FROM #T

 

/*本月出庫的*/

 

 

if(@IsYD='true')

begin

 

/*含預點的發料單*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT YDCKD_JH.CLXTBH, YDCKD_JH.KCDJ, SUM(YDCKD_JH.SL) AS SJSL,

 SUM(YDCKD_JH.JE) AS SJJE FROM YDCKD_DJ inner join YDCKD_JH ON YDCKD_DJ.DJXTBH=YDCKD_JH.CKD_DJ_DJXTBH

WHERE YDCKD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi  GROUP BY YDCKD_JH.CLXTBH, YDCKD_JH.KCDJ

 

/*直進直出出庫*/

 INSERT INTO #T(CLBH,DJ,SL,JE) SELECT YDZJZC_JH.CLXTBH, YDZJZC_JH.CGDJ,sum(YDZJZC_JH.SL) as SJSL,sum(YDZJZC_JH.CKJE) as SJJE

FROM  YDZJZC_DJ INNER JOIN YDZJZC_JH ON YDZJZC_DJ.DJXTBH = YDZJZC_JH.DJXTBH WHERE YDZJZC_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY YDZJZC_JH.CLXTBH,YDZJZC_JH.CGDJ

 

end

 

 

/*發料的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT CKD_JH.CLXTBH, CKD_JH.KCDJ, SUM(CKD_JH.SL) AS SJSL,

SUM(CKD_JH.JE) AS SJJE FROM CKD_DJ inner join CKD_JH ON CKD_DJ.DJXTBH=CKD_JH.CKD_DJ_DJXTBH

WHERE CKD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY CKD_JH.CLXTBH, CKD_JH.KCDJ

 

/*發料退回的*/

INSERT INTO #T(CLBH,DJ,SL,JE)  SELECT CKTHD_JH.CLXTBH, CKTHD_JH.KCDJ, -SUM(CKTHD_JH.SL) AS SJSL,

-SUM(CKTHD_JH.JE) AS SJJE FROM CKTHD_DJ inner join CKTHD_JH ON CKTHD_DJ.DJXTBH=CKTHD_JH.DJXTBH

 WHERE CKTHD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY CKTHD_JH.CLXTBH, CKTHD_JH.KCDJ

 

/*調撥出庫的*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT DBCKD_JH.CLXTBH, DBCKD_JH.KCDJ, SUM(DBCKD_JH.SL) AS SJSL,

SUM(DBCKD_JH.JE) AS SJJE FROM DBCKD_DJ inner join DBCKD_JH ON DBCKD_DJ.DJXTBH=DBCKD_JH.DJXTBH

WHERE DBCKD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY DBCKD_JH.CLXTBH, DBCKD_JH.KCDJ

 

/*調撥出庫退貨單*/

INSERT INTO #T(CLBH,DJ,SL,JE) SELECT DBCKTHD_JH.CLXTBH, DBCKTHD_JH.KCDJ, -SUM(DBCKTHD_JH.SL)

AS SJSL, -SUM(DBCKTHD_JH.JE) AS SJJE FROM DBCKTHD_DJ inner join DBCKTHD_JH ON DBCKTHD_DJ.DJXTBH=DBCKTHD_JH.DJXTBH

WHERE DBCKTHD_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY DBCKTHD_JH.CLXTBH, DBCKTHD_JH.KCDJ

/*直進直出出庫*/

 INSERT INTO #T(CLBH,DJ,SL,JE) SELECT ZJZC_JH.CLXTBH, ZJZC_JH.CGDJ,sum(ZJZC_JH.SL) as SJSL,sum(ZJZC_JH.CKJE) as SJJE

FROM  ZJZC_DJ INNER JOIN ZJZC_JH ON ZJZC_DJ.DJXTBH = ZJZC_JH.DJXTBH WHERE ZJZC_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY ZJZC_JH.CLXTBH,ZJZC_JH.CGDJ

/*直進直出chu庫退貨*/

 INSERT INTO #T(CLBH,DJ,SL,JE) SELECT ZJZCTH_JH.CLXTBH,ZJZCTH_JH.CGTHDJ, -sum(ZJZCTH_JH.SL) as SJSL,-sum(ZJZCTH_JH.CKTHJE) as SJJE

FROM  ZJZCTH_DJ INNER JOIN ZJZCTH_JH ON ZJZCTH_DJ.DJXTBH = ZJZCTH_JH.DJXTBH WHERE ZJZCTH_DJ.RQ BETWEEN @QiShiRiQi AND @ZhongZhiRiQi GROUP BY ZJZCTH_JH.CLXTBH,ZJZCTH_JH.CGTHDJ

 

INSERT INTO #ShouZhiCunMingXi(CLBH,DJ,SL,JE,Lie) SELECT CLBH,DJ,SUM(SL) AS SL,SUM(JE) AS JE,'出庫' AS LB

 FROM #T GROUP BY CLBH,DJ

 

DELETE FROM #T

 

--第一步:根據系統編號、列、單價分組求和

select CLBH,DJ,sum(SL) as SL,sum(JE) as JE,Lie

                            into #TempSZCMX

 from #ShouZhiCunMingXi group by Lie, CLBH , DJ order by Lie,CLBH

 

 --第二步:列轉行,分組求和

 insert into #TempLastResults

SELECT YJ,EJ,

         MoJi=(CASE WHEN grouping(YJ) = 1 THEN '0' 

                            WHEN grouping(EJ) = 1 THEN [YJ]

                            when grouping(MoJi)=1 then [EJ] else MoJi END),

  DJ,

sum(SYSL) SYSL,SUM(SYJE) SYJE,SUM(BYSL) BYSL,SUM(BYJE) BYJE,

SUM(CKSL) CKSL,SUM(CKJE) CKJE,SUM(RKSL) RKSL,SUM(RKJE) RKJE

--into #TempLastResults

from

(

 

select CaiLiaoXinxi_1.SJ AS YJ,CaiLiaoXinxi_1.BH AS EJ,CaiLiaoXinxi.BH AS MoJi,DJ,

sum(case Lie when '上月' then SL else 0 end) as 'SYSL',

                            sum(case Lie when '上月' then JE else 0 end) as 'SYJE',

                            sum(case Lie when '本月' then SL else 0 end) as 'BYSL',

                            sum(case Lie when '本月' then JE else 0 end) as 'BYJE',

                            sum(case Lie when '出庫' then SL else 0 end) as 'CKSL',

                            sum(case Lie when '出庫' then JE else 0 end) as 'CKJE',

                            sum(case Lie when '入庫' then SL else 0 end) as 'RKSL',

                            sum(case Lie when '入庫' then JE else 0 end) as 'RKJE'

                            from #TempSZCMX inner join CaiLiaoXinxi ON #TempSZCMX.CLBH =CaiLiaoXinxi.XTBH

                            INNER JOIN CaiLiaoXinxi  CaiLiaoXinxi_1 ON CaiLiaoXinxi.SJ=CaiLiaoXinxi_1.BH

                            GROUP BY CaiLiaoXinxi.BH ,CaiLiaoXinxi_1.BH,CaiLiaoXinxi_1.SJ,DJ

                            ) as MingXi

                            group by YJ,EJ,MoJi,DJ with rollup  having grouping(MoJi) =1 union all       

select CaiLiaoXinxi_1.SJ AS YJ,CaiLiaoXinxi_1.BH AS EJ,CaiLiaoXinxi.BH AS MoJi,DJ,

sum(case Lie when '上月' then SL else 0 end) as 'SYSL',

                            sum(case Lie when '上月' then JE else 0 end) as 'SYJE',

                            sum(case Lie when '本月' then SL else 0 end) as 'BYSL',

                            sum(case Lie when '本月' then JE else 0 end) as 'BYJE',

                            sum(case Lie when '出庫' then SL else 0 end) as 'CKSL',

                            sum(case Lie when '出庫' then JE else 0 end) as 'CKJE',

                            sum(case Lie when '入庫' then SL else 0 end) as 'RKSL',

                            sum(case Lie when '入庫' then JE else 0 end) as 'RKJE'

                            --into #TempLastResults

                            from #TempSZCMX inner join CaiLiaoXinxi ON #TempSZCMX.CLBH =CaiLiaoXinxi.XTBH

                            INNER JOIN CaiLiaoXinxi  CaiLiaoXinxi_1 ON CaiLiaoXinxi.SJ=CaiLiaoXinxi_1.BH

                            GROUP BY CaiLiaoXinxi.BH ,CaiLiaoXinxi_1.BH,CaiLiaoXinxi_1.SJ,DJ                     

--第三步:求最終結果

select MC,GG,DW,DJ,SYSL,SYJE,RKSL,RKJE,CKSL,CKJE,BYSL,BYJE

from #TempLastResults inner join

(

 SELECT '0' AS BH,'所有材料總計' AS MC,'' AS GG,'' AS DW

 UNION ALL

 SELECT BH,(MC+'  合計') AS MC,GG,DW FROM CaiLiaoXinxi WHERE SJ='0' and MJ=0

 UNION ALL SELECT BH,(MC+'  小計') AS MC,GG,DW FROM CaiLiaoXinxi WHERE SJ<>'0' AND MJ=0

 UNION ALL SELECT BH, MC,GG,DW FROM CaiLiaoXinxi WHERE MJ=1

 ) AS B on B.BH=#TempLastResults.MoJi and B.BH like @LeiBie order by B.BH

 

-------------------------------------------------------------------------------------------

在SQLServer中real是16位的浮點型,float是32位的,這點和C#的不同

SQLServer中的real和float分別對應C#中的float和double

 

 

------------------------完整的sql存儲過程案例,分頁;

USE [PM]

GO

/****** 對象:  StoredProcedure [dbo].[PItemPerMoney]    腳本日期: 07/11/2013 15:01:44 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Author:          <Author,,Name>

-- Create date: <Create Date,,>

-- Description: <Description,,>

-- =============================================

ALTER PROCEDURE  [dbo].[PItemPerMoney]

          (

          @PName varchar(100),

          @DName varchar(50),

          @begintime datetime,

          @OverTime datetime,

          @PerName varchar(50),

          @bePage int,

          @edpage int,

          @num int output

       )

as

BEGIN

----查詢利率

declare @YL varchar(10)

declare @SY varchar(10)

declare @GJJ varchar(10)

declare @YB varchar(10)

declare @XMGTS varchar(10)

declare @MonCount varchar(10)

declare @str nvarchar(4000)

--給利率賦值

select @YL=cast(YL AS varchar(10)),@SY=cast(SY AS varchar(10)),@GJJ=cast(GJJ AS varchar(10)),@YB=cast(YB AS varchar(10)),@XMGTS=cast(XMGTS AS varchar(10)) from PTaxRatioSet where Id=1

--查詢工做月份的月數

select @MonCount=CAST(datediff(mm,@begintime,@OverTime) as varchar(10))

IF @MonCount='0' or @MonCount is null

set @MonCount='1'

----查詢總條數

set @str=

'select @num=count(1) from View_PItemPer where 1=1 '

if(@PName<>'')

  set @str=@str+' and PName LIKE ''%'' + REPLACE(''' + @PName + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

if(@PerName<>'')

  set @str=@str+' and PerName LIKE ''%'' + REPLACE(''' + @PerName + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

if(@DName<>'')

  set @str=@str+' and DName LIKE ''%'' + REPLACE(''' + @DName + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

EXEC sp_executesql @str, N'@num INT OUTPUT', @num OUTPUT

----統計

set @str=

' select tt.* from (select row_number() over(order by t.Id) as rowid,t.*,t.Gang-t.Yl-t.Sy-t.Gjj-t.Yb as shuiqian,t.Gang-t.Xmgts as shifa from (select *,PMoney*'+@MonCount+' as Gang,PMoney*'+@MonCount+'*'+@YL+' as Yl, PMoney*'+@MonCount+'*'+@SY+' as Sy, PMoney*'+@MonCount+'*'+@GJJ+' as Gjj, PMoney*'+@MonCount+'*'+@YB+' as Yb, PMoney*'+@MonCount+'*'+@XMGTS+' as Xmgts from View_PItemPer where 1=1 '

if(@PName<>'')

  set @str=@str+' and PName LIKE ''%'' + REPLACE(''' + @PName + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

if(@PerName<>'')

  set @str=@str+' and PerName LIKE ''%'' + REPLACE(''' + @PerName + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

if(@DName<>'')

  set @str=@str+' and DName LIKE ''%'' + REPLACE(''' + @DName + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

SET @str=@str+') as t) as tt where tt.rowid between '+cast(@bePage as varchar(10))+' and '+cast(@edpage as varchar(10))

EXEC (@str)

END

--------------------------存儲過程須要注意:

設置拼接字符串變量@str必須是nvarchar類型,否則會報錯;

返回數量變量必須是:

EXEC sp_executesql @str, N'@num INT OUTPUT', @num OUTPUT

 

----------------

-----------------

-------------------根據身份證號判斷出生年月和工齡

  /// <summary>

        /// 出生日期

        /// </summary>

        public DateTime? Birth

        {

            get

            {

                if (_idcard.Length == 18)

                {

                    string birth = _idcard.Substring(6, 8);

                    string birth1 = birth.Substring(0, 4) + "-" + birth.Substring(4, 2) + "-" + birth.Substring(6, 2);

                    return Convert.ToDateTime(birth1);

                }

                else if (_idcard.Length == 15)

                {

                    string birth = _idcard.Substring(6, 6);

                    string birth1 ="19"+birth.Substring(0, 2) + "-" + birth.Substring(2, 2) + "-" + birth.Substring(4, 2);

                    return Convert.ToDateTime(birth1);

                }

                else

                {

                    return null;

                }

            }

        }

        /// <summary>

        /// 年齡

        /// </summary>

        public int Age

        {

            get

            {

                if (_idcard.Length == 18)

                {

                    string birth = _idcard.Substring(6, 8);

                    return DateTime.Now.Year-Convert.ToInt32(birth.Substring(0,4));

                }

                else if (_idcard.Length == 15)

                {

                    string birth = _idcard.Substring(6, 6);

                    return DateTime.Now.Year - Convert.ToInt32("19" + birth.Substring(0, 2));

                }

                else

                {

                    return 0;

                }

            }

        }

---------------------------------------------存儲過程判斷某一變量是否爲空

if(@PName<>'')

 

當將語句定義爲字符串時,應將全部變量轉化爲varchar類型,要否則會報錯;

-------

------------------------------好比:

if(@begintime<>'')

  set @str=@str+' and ApplyDate>='''+convert(varchar(100),@begintime)+''''

if(@OverTime<>'')

   set @str=@str+' and ApplyDate<='''+convert(varchar(100),@OverTime)+''''

---------------------------當有輸出參數執行字符串時;

EXEC sp_executesql @str, N'@num INT OUTPUT', @num OUTPUT

-------------行列轉換

SUM(CASE WHEN T.ParentName=''休假'' THEN T.alldays ELSE 0 END)

 

 

--------------------------js根據出生日期獲取年齡;

  $(function () {

            $("#txtAge").click(function () {

                var dateUser = new Date();

                var nowYear = dateUser.getFullYear();

                var dateUser1 = new Date($("#txtBirthDate").val());

                var birthYear = dateUser1.getFullYear();

                $("#txtAge").val(nowYear - birthYear);

                if ($("#txtAge").val() > 18) {

                    alert("年齡超過18歲,禁止 填寫");

                }

            });

        });

 

---------------------彙總模板:

------彙總數據

select a.id,a.PerId,a.allworkm,a.allrestm,a.allvalm,a.workdays,a.restdays,a.valmdays,a.alldays,a.allmoney,

b.Sex,b.IdCard,b.WorkDateQ,b.RestDateQ,b.ValDateQ,

case when ptag='2' then '全部人(彙總)' when ptag='1' then '我的(彙總)' else b.PerName end as PerName

 from(

select id,PerId,sum(workm) as allworkm,sum(restm) as allrestm,sum(valm) as allvalm,

sum(workdays) as workdays,sum(restdays) as restdays,sum(valmdays) as valmdays,

sum(alldays) as alldays,sum(workm+restm+valm) as allmoney,

case when grouping(PerId)=1 and grouping(id)=1  then '2' when grouping(id)=1 and grouping(PerId)=0  then '1' else '' end as Ptag

from #T group by PerId,Id with rollup) as a left join  View_PBTChild as b

on a.id=b.Id

END

------------------------------存儲過程模板

USE [PM]

GO

/****** 對象:  StoredProcedure [dbo].[PvalStastics]    腳本日期: 07/15/2013 10:27:40 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Author:          <Author,,Name>

-- Create date: <Create Date,,>

-- Description: <Description,,>

-- =============================================

ALTER PROCEDURE [dbo].[PvalStastics]

 (

          @PName varchar(100),

          @begintime datetime,

          @OverTime datetime,

          @PerName varchar(50),

          @bePage int,

          @edpage int,

          @num int output

  )

as

BEGIN

declare @str nvarchar(4000)

set @str=

'select @num=count(distinct PerId) from View_PvalApply where 1=1 '

if(@PName<>'')

  set @str=@str+' and PName LIKE ''%'' + REPLACE(''' + @PName + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

if(@PerName<>'')

  set @str=@str+' and PerName LIKE ''%'' + REPLACE(''' + @PerName + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

if(@begintime<>'')

  set @str=@str+' and ApplyDate>='''+convert(varchar(100),@begintime)+''''

if(@OverTime<>'')

   set @str=@str+' and ApplyDate<='''+convert(varchar(100),@OverTime)+''''

EXEC sp_executesql @str, N'@num INT OUTPUT', @num OUTPUT

----統計

set @str=

' SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY TT.PerId) as rowid,TT.*,TT.qing+TT.xiu as allvaldays FROM (

SELECT T.PerId,T.PerName,T.PName,SUM(CASE WHEN T.ParentName=''請假'' THEN T.alldays ELSE 0 END) as qing,

SUM(CASE WHEN T.ParentName=''休假'' THEN T.alldays ELSE 0 END) as xiu FROM(SELECT PerId,PerName,PName,ParentName,SUM(ValDays) as alldays FROM View_PvalApply GROUP BY PerId,PerName,PName,ParentName

HAVING 1=1 '

if(@PName<>'')

  set @str=@str+' and PName LIKE ''%'' + REPLACE(''' + @PName + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

if(@PerName<>'')

  set @str=@str+' and PerName LIKE ''%'' + REPLACE(''' + @PerName + ''', ''%'', ''/%'') + ''%'' ESCAPE ''/'''

if(@begintime<>'')

  set @str=@str+' and ApplyDate>='''+convert(varchar(100),@begintime)+''''

if(@OverTime<>'')

   set @str=@str+' and ApplyDate<='''+convert(varchar(100),@OverTime)+''''

SET @str=@str+') as T GROUP BY T.PerId,T.PerName,T.PName) as TT) as TTT WHERE TTT.rowid BETWEEN '+cast(@bePage as varchar(10))+' and '+cast(@edpage as varchar(10))

EXEC (@str)

END

 

--------------------------------查詢年月季度的起始日期和結束日期的方法;

   DateTime starttime = wp.BeginTime;

        DateTime endtime = wp.OverTime;

        wp.OverTime = wp.BeginTime;

            while (wp.OverTime <=endtime)

            {

                switch(tag)

                {

                    //1:年2:季度3:月

                    case 1: wp.OverTime =DateProvider.LastDateOfYear(wp.BeginTime);break;

                    case 2:  wp.OverTime =DateProvider.LastDateOfQuarter(wp.BeginTime);break;

                    case 3: wp.OverTime = DateProvider.LastDateOfMonth(wp.BeginTime);break;

                }

                //查詢每一個時間間隔的數據

                SafePdLevel sp = GetData(wp);

                sp.dateId = wp.OverTime;

                list.Add(sp);

                wp.BeginTime = wp.OverTime.AddDays(1);

        }

 

----------------------------excel導入所有代碼:

  public static System.Data.DataTable DataTableforExcel(string strExcelFileName, string strSheetName,int columnsCount)

        {

            System.Data.DataTable dt = new System.Data.DataTable();

            for (int i = 0; i <columnsCount; i++)

            {

                dt.Columns.Add(new DataColumn());

            }

            Excel.Application excel = new Excel.Application();

            Excel.Workbook m_objBook = (Excel.Workbook)(excel.Workbooks.Add(strExcelFileName));

            Worksheet sheet = null;

            foreach (Worksheet wsheet in m_objBook.Worksheets)

            {

                if (wsheet.Name == strSheetName)

                {

                    sheet = wsheet;

                    break;

                }

            }

            if (sheet != null)

            {

                int row = 2;

                while (true)

                {

                    Range rName = sheet.Cells[row, 1] as Range;

                    if (rName.Text.ToString().Trim().Length == 0)

                    {

                        break;

                    }

                    DataRow dr = dt.NewRow();

                    for (int i = 0; i <columnsCount; i++)

                    {

                        Range rContent = sheet.Cells[row, i + 1] as Range;

                        dr[i] = rContent.Text;

                    }

                    dt.Rows.Add(dr);

                    row += 1;

                }

            }

            excel.Quit();

            return dt;

        }

    }

---開始導入

public partial class Personnel_PPersonImport: System.Web.UI.Page

{

    PPersonMessaManager pmm = new PPersonMessaManager();

    PPartManager ppm = new PPartManager();

    PDutyManager pdm = new PDutyManager();

    protected void btnadd_Click(object sender, EventArgs e)

    {

        if (this.FileUpload1.HasFile)

        {

            //上傳文件

            string path = Server.MapPath("../File/PersonImport/");

            FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName);

            //生成datatable

            string path1 = Server.MapPath("../File/PersonImport/"+FileUpload1.FileName);

            DataTable table = PM.Frame.DataFromExcel.DataTableforExcel(path1, "Sheet1",20);

            if (table != null && table.Rows.Count !=0)

            {

               Improt(table);

               Messabox.ShowError(this,"已成功導入");

            }

            else

            {

                Messabox.ShowError(this, "沒有數據要導入");

            }

        }

        else

        {

            Messabox.ShowError(this, "請選擇上傳的人員文件");

        }

    }

    protected void btnback_Click(object sender, EventArgs e)

    {

 

    }

    protected bool Improt(DataTable table)

    {

      

        for (int i = 0; i < table.Rows.Count; i++)

        {

            PPersonMessa pm = new PPersonMessa();

            pm.Id = pmm.GetMaxId();

            //部門

            PPart pp = new PPart();

            pp.PName = table.Rows[i][1].ToString().Trim();

            pp.SJ = -1;

            List<PPart> list = ppm.GetList(pp);

            if (list != null && list.Count != 0)

            {

                pm.PartId = new PPart {Id=list[0].Id};

            }

            //職位

            PDuty pd = new PDuty();

            pd.DName= table.Rows[i][9].ToString().Trim();

            List<PDuty> list1 = pdm.GetList(pd);

            if (list1 != null && list1.Count != 0)

            {

                pm.GangName = new PDuty { Id = list1[0].Id};

            }

            //其餘

            pm.PerName = table.Rows[i][2].ToString().Trim();

            pm.Sex = table.Rows[i][3].ToString().Trim();

            pm.Nation = table.Rows[i][4].ToString().Trim();

            pm.Address = table.Rows[i][5].ToString().Trim();

            pm.BirAddress = table.Rows[i][6].ToString().Trim();

            pm.Face= table.Rows[i][7].ToString().Trim();

            pm.DangTime= table.Rows[i][8].ToString().Trim();

            pm.IdCard = table.Rows[i][10].ToString().Trim();

            try

            {

                pm.WorkTime =Convert.ToDateTime(table.Rows[i][11].ToString().Trim());

            }

            catch { }

            pm.Education= table.Rows[i][12].ToString().Trim();

            pm.EducationTime = table.Rows[i][13].ToString().Trim();

            pm.School = table.Rows[i][14].ToString().Trim();

            pm.Major = table.Rows[i][15].ToString().Trim();

            pm.ZhiCheng = table.Rows[i][16].ToString().Trim();

            pm.ZiGe = table.Rows[i][17].ToString().Trim();

            pm.Phone= table.Rows[i][18].ToString().Trim();

            pm.PerState = table.Rows[i][19].ToString().Trim();

            //插入

            pmm.Add(pm);

        }

            return true;

 

    }

}

---------------------------------查詢是否存在某列

USE EF

SELECT COUNT(1) FROM syscolumns WHERE id=object_id('Orders') AND [name]='Name'

------

 public static bool Exists(SqlDataReader reader, string field)

        {

            bool b = false;

            for (int i = 0; i < reader.FieldCount; i++)

            {

                if (reader.GetName(i).Equals(field))

                {

                  

                    if (reader[field] != System.DBNull.Value)

                    {

                        b = true; break;

                    }

                }

            }

            return b;

        }

相關文章
相關標籤/搜索