[英]Calling SQL System function on DataTable in C#
我需要在DataTable上執行sql服務器系統功能。
DataTable有一個字符串值,例如“ 12345”,在此我需要一個在SUBSTRING(,0,2)之類的Sql服務器表中配置的子字符串。
我可以從數據庫表中獲取條件。 但是如何在DataTable中應用此條件?
有很多方法可以實現這一目標。
1-您可以創建一個調用函數的視圖,即:
Create View testView
As
Select
dbo.myFunction(parameter)
FROM dbo.TableName
2-您可以像羅斯在他的評論中提到的那樣使用C#Substring函數:
DataTableString.Substring(0, 2)
您可以在用於填充DataTable
的查詢中使用SUBSTRING
函數。 在您的問題中使用了SUBSTRING(0, 2)
,我想您要使用列的前兩個字母嗎? 在SQL Server中, SUBSTRING
從1開始,而在C#中,此函數從0開始。 您需要在SQL查詢中使用(Column, 1, 2)
返回前兩個字符。
string connStr = @"YourConnectionString;";
string cmd = @"SELECT SUBSTRING(ColumnA, 1, 2) AS ColumnA from YourSchema.YourTable";
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
DataTable dt = new DataTable();
//create data adapter from string with SQL command and SQL Connection object
SqlDataAdapter da = new SqlDataAdapter(cmd, conn);
//populate DataTable
da.Fill(dt);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.