简体   繁体   中英

Calling SQL System function on DataTable in C#

I need to execute the sql server system function over DataTable.

DataTable has a string value eg "12345", in this i need a substring which is configured in Sql server table like SUBSTRING(,0,2).

I'm able to get the condition from DB table. But how to apply this condition in DataTable?

There are many ways of achieving this.

1 - You can create a view that calls your function, ie:

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

2 - You can use C# Substring function as Ross mentioned in his comment:

DataTableString.Substring(0, 2)

You can use the SUBSTRING function in the query that is used to populate the DataTable . SUBSTRING(0, 2) was used in your question, I'm guessing you want the first two letters letters of the column? SUBSTRING in SQL Server starts at 1, while this same function begins at 0 in C#. You'll need to use (Column, 1, 2) in a SQL query to return the first two characters.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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