利用ADO.NET做資料庫查詢時,常常會使用到SqlParameter,
如果是使用在 IN 條件式的查詢,動態加入SqlParameter 參數就可以幫很大的忙。
方法:
///動態設定SqlParameters
List<SqlParameter> sqlParamList = new List<SqlParameter>();
sqlParamList.Add(new SqlParameter("@參數名稱A", "參數值"));
sqlParamList.Add(new SqlParameter("@參數名稱B", "參數值"));
///將List<SqlParameter>轉換為SqlParameter[]
SqlParameter[] sqlParams = sqlParamList.ToArray();
底下是我寫的一個簡單可動態設定SQL參數並回傳SQL查詢字串,可以用於IN條件式。
/// <summary>
/// 動態設定SQL參數: [SQL參數名稱][1~maxCnt]
/// </summary>
/// <param name="ParamList">List of SqlParameters</param>
/// <param name="Values">SQL參數值陣列</param>
/// <param name="paramNamePrefix">SQL參數名稱</param>
/// <param name="maxCnt">動態加入的次數</param>
/// <returns>Sql查詢文字(可用於IN 查詢)</returns>
public String SetSqlParameterList(
ref List<SqlParameter> sqlParamList, String[] Values, String paramNamePrefix, int maxCnt)
{
String sql_Params = String.Empty; //Sql查詢文字,如 @XXX1,@XXX2,@XXX3 ...
try
{
///動態設定SqlParameters
for (int i = 0; i < maxCnt; i++)
{
//指定SqlParameter Name
String paramName = String.Format("@{0}{1}", paramNamePrefix, i.ToString());
//加入到SqlParamList
sqlParamList.Add(new SqlParameter(paramName, Values[i]));
//設定Sql查詢文字
sql_Params += paramName + ","; //加入到sql_Params
}
sql_Params = sql_Params.Remove((sql_Params.Length - 1), 1); //去除最後一個逗號
return sql_Params;
}
catch (Exception)
{
throw;
}
}
文章分類
.NET 5
.NET Core
.NET FrameWork
3C
工作室佈告欄
心理探討
專案測試
軟體工程
開發流程
Agile
Algorithm
ALM
Android SDK
Angular
AngularJS
Architecture
ASP.NET
ASP.NET Core
Books
Bower
C#
C# (Extensions)
ChatBot
CLOUD
Comic
CSS
Dapper
Design Pattern
DevOps
Django
Docker
Domain Driven Design
Entity framework
EXCEL
Financial Derivatives
Firebase
Flask
Front-end
GIT
GitHub
Golang
GraphQL
Gulp
Identity Server
IIS
javascript
jQuery
Keyboard
L-I-F-E
LetsEncrypt
LINQ
LINUX
MongoDB
Multi-Thread
Nuget
Open Source
Oracle
OS
Performance issue
PostgreSQL
Project Management
Python
RabbitMQ
Redis
Redux
RxJS
SAP TM
Scrum
SEO
Sharepoint
Sql Server
SSRS
Study
Swagger
Team Foundation Server
TensorFlow
Testing
Toolkits
Tricking
Trouble Shooting
UML
Unit Test
Vim
Visual Studio
Visual SVN Server
VSCODE
Vue
Web Api
Web Service
WebStorm
Windows Application
WSL
沒有留言:
張貼留言