1. 程式人生 > >select 拼接字串查詢語句的 in (內容)

select 拼接字串查詢語句的 in (內容)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;


namespace testinArr
{
    class Program
    {
        static void Main(string[] args)
        {
            #region MyRegion


            //string[] toolNO = new string[] { "test編號123", "88888", "2282828282" };
            //StringBuilder sb = new StringBuilder();
            ////sb.Append("");
            //if (toolNO.Length > 0)
            //{
            //    if (toolNO.Length == 1)
            //    {
            //        sb.Append($" select * from ReportDataSource_ToolInfo where 工裝編號 ='{toolNO[0]}'");
            //    }
            //    else
            //    {
            //        sb.Append("select * from ReportDataSource_ToolInfo where 工裝編號 in( ");
            //        int i = 1;
            //        foreach (var item in toolNO)
            //        {
            //            sb.Append("'" + item + "'");
            //            if (i < toolNO.Length)
            //            {
            //                sb.Append(",");
            //            }
            //            i = i + 1;
            //        }
            //        sb.Append(") ");
            //    }
            //} 
            #endregion
            string[] toolNO = new string[] { "test編號123", "88888", "2282828282" };
            //string sb = Program.GetStringValues(toolNO);
            string sb = Program.GetStringValues();
            //string sb = Program.GetStringValues("test編號123", "88888", "2282828282");
            WriteLine(sb.ToString());
            ReadKey();
        }


        static string GetStringValues(params object[] toolNO)
        {
            StringBuilder sb = new StringBuilder();
            //sb.Append("");
            if (toolNO.Length > 0)
            {
                if (toolNO.Length == 1)
                {
                    sb.Append($" select * from ReportDataSource_ToolInfo where 工裝編號 ='{toolNO[0]}'");
                }
                else
                {
                    sb.Append("select * from ReportDataSource_ToolInfo where 工裝編號 in( ");
                    int i = 1;
                    foreach (var item in toolNO)
                    {
                        sb.Append("'" + item + "'");
                        if (i < toolNO.Length)
                        {
                            sb.Append(",");
                        }
                        i = i + 1;
                    }
                    sb.Append(") ");
                }
            }
            return sb.ToString();
        }
    }
}