3

I am using SQl CLR for parsing some table column. I want to execute the queries also in C# user defined function. Can somebody give an example to execute select and insert queries in the function?

Thank you in advance.

 SqlConnection objSqlConn;
    string connString = string.Empty;
    connString = "Data Source=(local);Initial Catalog=DB;User ID=uname;pwd=pass;Password=pass";
    objSqlConn = new SqlConnection(connString);
    objSqlConn.Open();

    string query = "Select count(*) FROM [DB].[dbo].[TableName]";
    SqlCommand cmdTotalCount = new SqlCommand(query, objSqlConn);
    cmdTotalCount.CommandTimeout = 0;
    string TotalCountValue = cmdTotalCount.ExecuteScalar().ToString();
    return TotalCountValue;

3 Answers 3

12

In CLR, you can use existing connection to run queries.

Simple, returning data to client:

var cmd = new SqlCommand("select * from [table]");
SqlContext.Pipe.ExecuteAndSend(cmd);

Returning data via SqlDataReader:

var con = new SqlConnection("context connection=true"); // using existing CLR context connection
var cmd = new SqlCommand("select * from table", con);
con.Open();
var rdr = cmd.ExecuteReader();
SqlContext.Pipe.Send(rdr);
rdr.Close();
con.Close();

Running other commands:

var con = new SqlConnection("context connection=true"); // using existing CLR context connection
var cmd = new SqlCommand("insert into [table] values ('ahoj')", con);
con.Open();
var rsa = cmd.ExecuteNonQuery();
con.Close();
Sign up to request clarification or add additional context in comments.

Comments

0

Once you switch to C# you execute queries like you'd normally do from your application (using ADO.NET's SqlConnection and SqlDataReader, using LINQ to SQL or using your custom build data layer).

1 Comment

Are you sure you could use Linq to Sql in SQLCLR? Does the database project even accept dbml file?
-2

To connect with the database you have to mention the database username and password in the connection string of your web.config file.

2 Comments

@sharmi Do you want an example to use select and insert query???Actually what are you expecting?
no, you want to use the existing connection as dizzy128 explained.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.