简体   繁体   English

在C#中的DataTable上调用SQL System函数

[英]Calling SQL System function on DataTable in C#

I need to execute the sql server system function over DataTable. 我需要在DataTable上执行sql服务器系统功能。

DataTable has a string value eg "12345", in this i need a substring which is configured in Sql server table like SUBSTRING(,0,2). DataTable有一个字符串值,例如“ 12345”,在此我需要一个在SUBSTRING(,0,2)之类的Sql服务器表中配置的子字符串。

I'm able to get the condition from DB table. 我可以从数据库表中获取条件。 But how to apply this condition in DataTable? 但是如何在DataTable中应用此条件?

There are many ways of achieving this. 有很多方法可以实现这一目标。

1 - You can create a view that calls your function, ie: 1-您可以创建一个调用函数的视图,即:

Create View testView
As
Select
dbo.myFunction(parameter)
FROM dbo.TableName

2 - You can use C# Substring function as Ross mentioned in his comment: 2-您可以像罗斯在他的评论中提到的那样使用C#Substring函数:

DataTableString.Substring(0, 2)

You can use the SUBSTRING function in the query that is used to populate the DataTable . 您可以在用于填充DataTable的查询中使用SUBSTRING函数。 SUBSTRING(0, 2) was used in your question, I'm guessing you want the first two letters letters of the column? 在您的问题中使用了SUBSTRING(0, 2) ,我想您要使用列的前两个字母吗? SUBSTRING in SQL Server starts at 1, while this same function begins at 0 in C#. 在SQL Server中, SUBSTRING从1开始,而在C#中,此函数从0开始。 You'll need to use (Column, 1, 2) in a SQL query to return the first two characters. 您需要在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM