2019年10月28日 星期一

Oracle x Table欄位 x 新增修改刪除




--先查詢table
select * from Table1;

--新增欄位
alter table Table1 add column1 varchar(20) default '' not null;

--修改一筆欄位
alter table Table1 modify column1 varchar(90);

--刪除欄位
alter table Table1 drop column column1;




2018年9月6日 星期四

Oracle x 刪除 x 大量重複資料


參考資料 : 掃文資訊

做了第一次後沒將SQL存起來,想說下次用就會了,結果還是忘記,這次記在這裡下次就可以來這裡看


--1.先找到重複資料的rowid,並找出rowid最大或最小值,作為刪除的條件
select min(rowid) from yourTable group by TableColumn having count(TableColumn) > 1;

--2.根據TableColumn找出數量大於1的重複資料
select TableColumn from yourTable group by TableColumn having count(TableColumn) > 1;

--3.根據上兩個條件進行執行刪除操作
delete from yourTable t where t.TableColumn in (
select TableColumn from yourTable group by TableColumn having count(TableColumn) > 1
)
and rowid not in (
select min(rowid) from yourTable group by TableColumn having count(TableColumn) > 1
);

--第一點的min(rowid)可以改成max(rowid),差別在於min會找出最早建立的資料(舊資料);max會找出最晚建立的資料(新資料)

2018年6月20日 星期三

C# x 1到100陣列 x 隨機不重複


昨天去xx看到不錯的考題,當下沒有解出來,寫了不隨機不重複的Code,後來回家想想才發現原來這麼簡單...



using System;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rd = new Random();
            string strNum="";
            int[] ai = new int[100];
            int rNum;
            for (int i = 1; i <= 100; i++)
            {
                rNum = rd.Next(1, 101);//取亂數
                if (Array.IndexOf(ai, rNum) == -1)//用Array.IndexOf判斷有沒有重複,沒有重複的話回傳值就是-1
                {
                    ai[i - 1] = rNum;
                }
                else//用Array.IndexOf判斷有沒有重複,有重複就會到這裡
                {
                    while (Array.IndexOf(ai, rNum) != -1)//如果不等於 -1 那就在重新跑一次亂數取值,直到等於-1
                    {
                        rNum = rd.Next(1, 101);
                    }
                    ai[i - 1] = rNum;//Array.IndexOf = -1 就會跳出while迴圈 走到這裡
                }
            }

            foreach (int strnum in ai) //將陣列的值取出
            {
                strNum += strnum.ToString()+" , ";
            }
            Console.WriteLine(strNum);
            Console.ReadLine();
        }
    }
}

2017年10月20日 星期五

C# x WebService x 移除


看了 當麻許的Web Service移除 這篇

然後覺得他遇到的狀況跟我差不多

然後自己又琢磨了一下

然後我的開發工具是VS2015、WebSite、Framework4.5

紅字是重點


///////////以下寫在.asmx裡面///////////
using System;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web.Services;
using System.Web.Script.Services;


namespace WebSite1
{
    [WebService(Namespace = "",Description ="")]
    [System.ComponentModel.ToolboxItem(false)]
    public class iWS : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void PostGetData()
        {
            try
            {
                Stream s = System.Web.HttpContext.Current.Request.InputStream;
                byte[] b = new byte[s.Length];
                s.Read(b, 0, (int)s.Length);
                string strjson = Encoding.UTF8.GetString(b);
                JObject jObjt = JObject.Parse(strjson);
                Context.Response.Output.Write(JsonConvert.SerializeObject(jObjt, Formatting.Indented));
            }
            catch (Exception ex)
            {
                Context.Response.Output.Write(JsonConvert.SerializeObject(ex.Message, Formatting.Indented));
            }
        }
    }
}
///////////以上寫在.asmx裡面///////////



///////////以下Web.config///////////
 <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
        <add name="Documentation"/>
      </protocols>
      <conformanceWarnings>
        <remove name='BasicProfile1_1'/>
      </conformanceWarnings>
    </webServices>
    <pages controlRenderingCompatibilityVersion="4.0"/>
  </system.web>
</configuration>
///////////以上Web.config///////////




參考資料 :
https://dotblogs.com.tw/junegoat/2012/09/10/c-sharp-webservice-remove-xmlns
https://stackoverflow.com/questions/12705380/remove-xml-tag-while-creating-web-service-in-asp-net
https://taskyam.israports.co.il/TaskYamWS/GeneralWebServices.asmx
https://social.msdn.microsoft.com/Forums/zh-TW/be1c812b-503e-4d35-9f0c-9f12b9aaf406/how-to-remove-xmlns-attribute-from-webservice-response?forum=asmxandxml





2017年10月8日 星期日

C# x WebService x JSON x 接收及傳值


WebService 接收這個部分找了超多資料,搞了三天才搞定

-------以下WebService的程式碼,寫在asmx裡面

using System.Web.Services;
using System.Web.Script.Services;
using System.IO;
using System.Text;
using Newtonsoft.Json.Linq;

namespace WebService
{
    [WebService(Namespace = "http://microsoft.com/webservices/")]
    public class iWS : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

        public string PostGetData()
        {
            //應用程式呼叫的網址 : "http://localhost:54756/iWS.asmx/PostGetData"

            Stream s = System.Web.HttpContext.Current.Request.InputStream;
            byte[] b = new byte[s.Length];
            s.Read(b, 0, (int)s.Length);
            string aa = Encoding.UTF8.GetString(b);
            return aa;
        }
    }
}
-------以上WebService的程式碼,寫在asmx裡面



-------以下ConsoleApplication,寫在Program.cs裡面
using System;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net;
using System.IO;
using System.Data.SqlClient;
using System.Data;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string targetUrl = "http://localhost/iWS.asmx/PostGetData";

            string connString = "你資料庫的位置";
            byte[] postData;
            string jsonStr;
            try
            {
                string strSQL = "SELECT 'H123' as a, " + "\r\n" +
                                          "'56789' as b, " + "\r\n" +
                                          "'2' as c, ";

                SqlConnection connSQL = new SqlConnection(connString);
                connSQL.Open();
                SqlCommand comm = new SqlCommand(strSQL, connSQL);
                SqlDataReader dr = comm.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);
                dr.Close();
                comm.Dispose();
                connSQL.Close();
                int dtCount = dt.Rows.Count;

                for (int i = 0; i < dtCount; i++)
                {
                    JObject obj = new JObject(
                                                    new JProperty("a", dt.Rows[i][0].ToString()),
                                                    new JProperty("b", dt.Rows[i][1].ToString()),
                                                    new JProperty("c", dt.Rows[i][2].ToString())
                                                );

                    jsonStr = JsonConvert.SerializeObject(obj, Formatting.Indented);
                    postData = Encoding.UTF8.GetBytes(jsonStr);

                    HttpWebRequest request = HttpWebRequest.Create(targetUrl) as HttpWebRequest;
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Timeout = 30000;
                    request.ContentLength = postData.Length;
                    // 寫入 Post Body Message 資料流
                    using (Stream st = request.GetRequestStream())
                    {
                        st.Write(postData, 0, postData.Length);
                        Console.WriteLine(jsonStr);
                    }
                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                        {
                            string result = sr.ReadToEnd();
                            Console.WriteLine(result);

                        }
                    }
                }
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
    }
}
-------以上ConsoleApplication,寫在Program.cs裡面


參考資料 :
http://www.itread01.com/articles/1478475314.html
https://kknews.cc/zh-tw/other/4egm2v.html












2017年8月16日 星期三

C# x Timer x 定時執行


C# x Timer x 定時執行

Form裡面要有 :

Button *1
TextBox1 *1


/////////////////////以下 程式碼/////////////////////

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication31
{
    public partial class Form1 : Form
    {
        System.Timers.Timer testTimer;
        int intNum;
        public Form1()
        {
            InitializeComponent();
        }

        public void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            TextBox1.Text = TextBox1.Text + "\n\n" + intNum.ToString() ;
            intNum = intNum + 1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "Star")
            {
                testTimer = new System.Timers.Timer(2000);//定時週期2秒
                testTimer.Elapsed += myTimer_Elapsed;//每兩秒做這件事
                testTimer.AutoReset = true; //是否不斷重複定時器操作
                testTimer.Enabled = true; //定時器啟動
                Control.CheckForIllegalCrossThreadCalls = false;
                button1.Text = "Stop";
            }
            else
            {
                testTimer.Close();
                testTimer.Dispose();
                TextBox1.Text = TextBox1.Text + "\n\n" + "Stop";
                button1.Text = "Star";
            }
        }
    }
}


/////////////////////以上 程式碼/////////////////////


執行畫面






















參考資料 : http://blog.csdn.net/kankankankan2222/article/details/8249602

2017年8月15日 星期二

C# x 判斷路經尋找 x 檔案數量 x 依副檔名找檔名


C# x 判斷路經尋找 x 檔案數量 x 依副檔名找檔名


自動列印標籤用


Form裡面要有 :

Button *1
Label *1

/////////////////////以下 程式碼/////////////////////

using System;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApplication32
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(@"D:\test");
            DataGridView dgv = new DataGridView();
            int txtFileCount = dirInfo.GetFiles("*.txt").Length;
            if (txtFileCount != 0)
            {
                label1.Text = dirInfo.GetFiles("*.txt", SearchOption.AllDirectories)[0].ToString();
            }
        }
    }
}

/////////////////////以上 程式碼/////////////////////

執行畫面

























參考資料 : https://dotblogs.com.tw/dc690216/2009/09/17/10684
                   http://ithelp.ithome.com.tw/articles/10029065




2017年8月11日 星期五

C# x 指定檔案路徑 x 列印 x notifyIcon應用


C# x 指定檔案路徑 x 列印 x notifyIcon應用

Form裡面要有 :

Button *1
notifyicon *1
contextmenustrip *1
printdocument *1





/////////////////////以下 程式碼/////////////////////

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication30
{
    public partial class Form1 : Form
    {
        System.IO.StreamReader fileToPrint;
        System.Drawing.Font printFont;

        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            notifyIcon1.Text = "常駐程式";
        }

        private void notifyIcon1_MouseMove(object sender, MouseEventArgs e)
        {
            notifyIcon1.ShowBalloonTip(3000);
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.notifyIcon1.Visible = true;
                this.Hide();
            }
            else
            {
                this.notifyIcon1.Visible = false;
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void OpenTMS_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void ExitCMS_Click(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
            System.GC.Collect();
            System.Environment.Exit(System.Environment.ExitCode);

        }

        private void button1_Click(object sender, EventArgs e)
        {

            fileToPrint = new System.IO.StreamReader(@"D:\test.txt");
            printFont = new System.Drawing.Font("Arial", 10);
            printDocument1.Print();
            fileToPrint.Close();
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            float yPos = 0f;
            int count = 0;
            float leftMargin = e.MarginBounds.Left;
            float topMargin = e.MarginBounds.Top;
            string line = null;
            float linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics);
            while (count < linesPerPage)
            {
                line = fileToPrint.ReadLine();
                if (line == null)
                {
                    break;
                }
                yPos = topMargin + count * printFont.GetHeight(e.Graphics);
                e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
                count++;
            }
            if (line != null)
            {
                e.HasMorePages = true;
            }
        }
    }
}


/////////////////////以上 程式碼/////////////////////

執行畫面 : 
























參考資料 : https://dotblogs.com.tw/chou/archive/2009/02/25/7284.aspx
                    http://ms-net.blogspot.tw/2008/04/notifyicon-contextmenustrip.html





2017年8月2日 星期三

C# x dateTimePicker x datagridview x 儲存格結合


C# x dateTimePicker x datagridview x 儲存格結合

比原出處多了點東西 : 標題列不可以點、不會改掉其他儲存格

Form裡面要有 :

DataGridView * 1

/////////////////////以下 程式碼/////////////////////
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication33
{
    public partial class Form1 : Form
    {
        DateTimePicker oDateTimePicker = new DateTimePicker();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<MyData> oMyDataList = new List<MyData>();

            MyData obj1 = new MyData(1, DateTime.Now, "John");
            MyData obj2 = new MyData(2, DateTime.Now, "Sam");
            MyData obj3 = new MyData(3, DateTime.Now, "Ray");

            oMyDataList.Add(obj1);
            oMyDataList.Add(obj2);
            oMyDataList.Add(obj3);

            dataGridView1.DataSource = oMyDataList;
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1 && e.RowIndex>=0)
            {
                dataGridView1.Controls.Add(oDateTimePicker);
                oDateTimePicker.Format = DateTimePickerFormat.Short;
                Rectangle oRectangle = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
                oDateTimePicker.Size = new Size(oRectangle.Width, oRectangle.Height);
                oDateTimePicker.Location = new Point(oRectangle.X, oRectangle.Y);
                oDateTimePicker.CloseUp += new EventHandler(oDateTimePicker_CloseUp);
                oDateTimePicker.TextChanged += new EventHandler(dateTimePicker_OnTextChange);
                oDateTimePicker.Visible = true;
            }
            else
            {
                oDateTimePicker.Visible = false;
            }
        }
        public void dateTimePicker_OnTextChange(object sender, EventArgs e)
        {
            dataGridView1.CurrentCell.Value = oDateTimePicker.Text.ToString();
        }
        public void oDateTimePicker_CloseUp(object sender, EventArgs e)
        {
            oDateTimePicker.Visible = false;
        }
    }
    class MyData
    {
        public int ID { get; set; }
        public DateTime Date { get; set; }
        public string Name { get; set; }
        public MyData(int id, DateTime dt, string name)
        {
            ID = id;
            Date = dt;
            Name = name;
        }
    }
}

/////////////////////以上 程式碼/////////////////////



執行畫面





























參考資料 : http://www.c-sharpcorner.com/UploadFile/0f68f2/embedding-calendar-datetimepicker-control-into-datagridvie586/

2017年7月27日 星期四

C# x 日期變化


//改變日期format

string startStr = start.ToString("yyyy-MM-dd HH:mm:ss");

DateTime dt = Convert.ToDateTime(startStr);//轉回DateTime

P.S format 大小寫意義不同: MM=month, mm=Minutes, HH=24hours, hh=12hours

//日期時間相加減

DateTime start = Convert.ToDateTime("2011-04-25 15:50:39");

DateTime end = Convert.ToDateTime("2011-05-02 15:50:39");

TimeSpan ts = end.subtract(start); //兩時間天數相減

double dayCount = ts.Days; //相距天數

//目前時間

DateTime dt = DateTime.Now;

//本周周一

DateTime startWeek = dt.AddDays(1 - Convert.ToInt32(dt.DayOfWeek.ToString("d")));

//本周周日

DateTime endWeek = startWeek.AddDays(6);

//本月月初

DateTime startMonth = dt.AddDays(1 - dt.Day);

//本月月末

DateTime endMonth = startMonth.AddMonths(1).AddDays(-1);



參考資料 : http://bluemuta38.pixnet.net/blog/post/61533149-%E5%90%84%E7%A8%AE%E6%97%A5%E6%9C%9F%E6%99%82%E9%96%93%E8%A8%88%E7%AE%97

2017年7月20日 星期四

TSQL x 建立資料表的建議


重點 :
  1. ID為GUID是T1資料表的Primary Key,指定為非叢集索引
  2. a1,a2不會重複的欄位設定為叢集索引


CREATE TABLE [dbo].[T1]
(
[ID_Key] uniqueidentifier DEFAULT NEWSEQUENTIALID() NOT NULL,
[a1] [nvarchar](10)   NOT NULL,
[a2] [nvarchar](10)   NOT NULL,
[a3] [nvarchar](10)   NULL,
[a4] [datetime]          NULL,
[a5] [datetime]          NULL,
[a6] [decimal](12, 4) NULL,
[a7] [nvarchar](10)   NULL,
[a8] [nvarchar](10)   NULL,
[a9] [decimal](12, 4) NULL,
CONSTRAINT [PK_T1] PRIMARY KEY NONCLUSTERED
(
     ID_Key ASC
))
CREATE CLUSTERED INDEX CL01 ON T1(a1,a2 asc)



參考資料 :
http://blog.darkthread.net/post-2016-01-29-guid-as-pk-on-db.aspx



2016年9月8日 星期四

TSQL x 具參數的『多重陳述資料表值』函數 x FUNCTION


繼上次『具參數內嵌資料表值』函數  FUNCTION 後,今天剛好用到『多重陳述資料表值函數』就順便紀錄、複習一下其他種SQL-SERVER的函數

1.純量值函數
2.內嵌資料表值函數
3.多重陳述資料表值函數



1. 純量值函數 SCALAR FUNCTION

CREATE FUNCTION 年資 (@開始工作時間,@現在or結束工作時間)
RETURNS MONEY
AS
BEGIN

     DECLARE @結果 AS MONEY

     SET @結果 = YEAR(@開始工作時間) - YEAR(@現在or結束工作時間)

     RETURN @結果

END
;

2.內嵌資料表值函數  INLINE TABLE-VALUED FUNCTION

CREATE FUNCTION 員工資料 (@INPUT_部門)
RETURNS TABLE
AS
RETURN
(
     SELECT 部門,員編,姓名,性別,職務
          FROM 員工基本檔
               WHERE 部門 = @INPUT部門
)
;

3.多重陳述資料表值函數 MULTISTATEMENT TABLE-VALUED FUNCTION

CREATE FUNCTION 誰是代理人 (@INPUT_部門,@INPUT_員工姓名)
RETURNS @回傳的TABLE TABLE
(
    姓名 varchar(10),
    電話 varchar(10)
)
AS
BEGIN
     DECLARE  @暫存欄位  varchar(10);

     SELECT @暫存欄位 = 代理人
          FROM 員工基本檔
               WHERE 部門=@INPUT_部門
                AND 員工姓名 = @INPUT_員工姓名

     INSERT @回傳的TABLE
         SELECT  姓名,電話
              FROM 員工基本檔
                   WHERE 員工姓名=@暫存欄位
RETURN
END
;











2016年8月31日 星期三

TSQL x 具參數的『內嵌資料表值』函數 x Function

因為公司ERP系統是跟外面買的(非自行開發),現在如果要報表產生程式中沒有廠商設定好到的欄位,該怎麼辦

我第一個想到的就是直接再報表裡面寫CommandText丟SQL進去撈資料,但報表的程式碼看起來非常大一串

後來前輩叫我用SQL-SERVER的Function,想說T-SQL不熟就來練練吧

具參數的"內嵌資料表值"函數 (INLINE TABLE-VALUED FUNCTION)



CREATE FUNCTION INVTEST (@A varchar(20),
                                                        @B varchar(20),
                                                        @C varchar(20))
RETURNS TABLE
AS
RETURN
SELECT X.column1 ,  
                Y.column1 ,  
                CAST(ISNULL(X.column2,0) AS numeric(10,2)) ,        
                CAST(ISNULL(Y.column2,0) AS numeric(10,2))      
FROM TABLE_NAME_1 X            
LEFT JOIN TABLE_NAME_3 Y      
ON ...          
AND ...
WHERE X.column5=@A        
      AND X.column6=@B
      AND X.column7=@C
UNION ALL                      
SELECT X.column ,  
                Y.column ,  
                CAST(ISNULL(X.column,0) AS numeric(10,2)) ,                
                CAST(ISNULL(Y.column,0) AS numeric(10,2))              
FROM TABLE_NAME_2 X            
LEFT JOIN TABLE_NAME_3 Y      
ON ...          
AND ...
AND ...
WHERE X.column5=@A        
      AND X.column6=@B
      AND X.column7=@C  

--CAST(ISNULL(X.column2,0) AS numeric(10,2)) ,
-- 處理如果X.column2是空值,就帶0,再將處理完的值轉成數值 : 整數位8碼,小數位2碼    
--UNION ALL上面跟下面的主要TABLE不一樣
--@A , @B , @C 要丟進去查詢的值
;

執行
SELECT * FROM dbo.INVTEST(A,B,C)


2016年8月25日 星期四

TSQL x 日期時間的顯示方法 x Time

以前使用Oracle,如果要篩選時間資料的話,只要下to_char('欄位名稱','yyyymmdd')
或是 to_date('欄位名稱','yyyymmdd') 就可以了

'yyyymmdd' 可以換成 'yyyy-mm-dd' 、'yyyy/mm/dd' 產生出不同的樣式出來
在T-SQL中,這種語法變成,CONVERT(CHAR(8),欄位名稱,112) 
CONVERT語法最後一個涵式是 "日期格式" (上述的 112)

112 : yyyymmdd   舉例 : 20160101
111 : yyyy/mm/dd  舉例 : 2016/01/01
102 : yyyy.mm.dd  舉例 : 2016.01.01
120 : yyyy-mm-dd  舉例 : 2016-01-01
如果要有符號   /.-  的話長度就要設定char(10)

若只有char會顯示時分秒 >> CONVERT(CHAR,欄位名稱,112)

所以 Oracle : to_date('日期欄位','yyyymmdd')  =  MSSQL : CONVERT(char(8),日期欄位,112)

其他格式或相關資料可以參考 MSDN 的 CAST 和 CONVERT (Transact-SQL)