SQL CLR executes with multiples sql statements - sql-server

I need a SQL CLR that executes with multiple sql statements, i.e., with update queries, select queries and stored procedures to create a stored procedure in the database
[Microsoft.SqlServer.Server.SqlProcedure]
public static void pExecuteAuthorization(SqlInt32 id) {
string name = "";
string surname = "";
using (SqlConnection connection = new SqlConnection("context connection=true")) {
string sql = "UPDATE tTest SET Sequence = ISNULL(Sequence,0) + 1 WHERE Id = " + id;
using (SqlCommand command = new SqlCommand(sql, connection)) {
connection.Open();
int valRet = command.ExecuteNonQuery();
if (valRet > 0)
{
command.CommandText = "SELECT Name, Surname FROM tAuthorization WHERE Id = 1";
SqlParameter param = command.Parameters.Add("#Name", SqlDbType.VarChar, 50);
param.Direction = ParameterDirection.Output;
param = command.Parameters.Add("#Surname", SqlDbType.VarChar, 20);
param.Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
name = command.Parameters["#Name"].Value.ToString();
surname = command.Parameters["#Surname"].Value.ToString();
if (name != "" && surname != "")
{
command.CommandText = "SELECT ...";
SqlDataReader dr = command.ExecuteReader();
if (dr.Read())
{
//other queries more
}
}
}
}
SqlContext.Pipe.ExecuteAndSend(command);
}
}
But when I execute the sp created, only I get the result of select, and it does not execute the other queries

Related

How to assign SQL #Action flag in ASP.NET MVC DAL class using single stored procedure?

Here is my SQL query:
CREATE PROCEDURE User_CRUD
#Action varchar(20),
#eno int,
#ename varchar(50),
#salary money
AS
IF #Action = 'Insert'
BEGIN
INSERT INTO employee (eno, ename, salary)
VALUES (#eno, #ename, #salary)
END
ELSE IF #Action = 'Update'
BEGIN
UPDATE employee
SET ename = #ename, salary = #salary
WHERE eno = #eno
END
ELSE IF #Action = 'Delete'
BEGIN
DELETE FROM employee
WHERE eno =#eno
END
ELSE IF #Action = 'Getemp'
BEGIN
SELECT *
FROM employee
END
ELSE IF #Action = 'Search'
BEGIN
SELECT ename, salary
FROM employee
WHERE eno = #eno
END
And here is my DAL class file:
public int AddEmployee(Models.Employee e1)
{
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "Insert");
cmd.Parameters.AddWithValue("#eno", e1.Eno);
cmd.Parameters.AddWithValue("#ename", e1.Ename);
cmd.Parameters.AddWithValue("#salary", e1.Salary);
e1.RollNo = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
return e1.RollNo;
}
public int DeleteEmployee(Models.Employee e1)
{
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "Delete");
cmd.Parameters.AddWithValue("#eno",e1.Eno);
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
public int UpdateEmployee(Models.Employee e1)
{
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "Update");
cmd.Parameters.AddWithValue("#eno", e1.Eno);
cmd.Parameters.AddWithValue("#ename", e1.Ename);
cmd.Parameters.AddWithValue("#salary", e1.Salary);
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
public List<Models.Employee> GetEmployee()
{
List<Models.Employee> li = new List<Models.Employee>();
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while(dr.Read())
{
Models.Employee e1= new Models.Employee();
e1.RollNo = int.Parse(dr[0].ToString());
e1.Eno = int.Parse(dr[1].ToString());
e1.Ename = dr[2].ToString();
e1.Salary = double.Parse(dr[3].ToString());
cmd.Parameters.AddWithValue("#Action", "Getemp");
li.Add(e1);
}
}
return li;
}
public Models.Employee SearchEmp(Models.Employee e1)
{
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
cmd.CommandType= CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "Search");
cmd.Parameters.AddWithValue("#eno", e1.Eno);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (dr.Read())
{
e1.Ename= dr[0].ToString();
e1.Salary= double.Parse(dr[1].ToString());
}
}
con.Close();
return e1;
}
When I try to perform some crud operation using single procedure it is showing error in GetEmployee() method like #Action method which was not supplied. SearchEmp() method is also showing the same error.
Can anyone help me with this?
Thanks in advance

How to connect to SQL Server

I am trying to connect to my database, I am beginner to the repository, dependency injection. I couldn't connect to the database.
How can I resolve this issue?
This is my code:
Controller:
public ActionResult Create(FormCollection collection)
{
try
{
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Repository:
public UserMaster Add(UserMaster item)
{
using (SqlConnection sqlCon = new SqlConnection(connectionstring))
{
sqlCon.Open();
string query = "INSERT INTO Employee
VALUES (#ID, #Name, #City, #Address)";
for (int i = 0; i <= 100; i++)
{
SqlCommand sqlcmd = new SqlCommand(query, sqlCon);
sqlcmd.Parameters.AddWithValue(ID = i, Name = "newride", City = "newride", Address = "USA");
}
}
return item;
}
The connection is made using the connection string and the SqlConnection class - that seems to be fine in your code.
BUT: the way you're trying to insert values is all wrong - you need to use something like this:
using (SqlConnection sqlCon = new SqlConnection(connectionstring))
{
sqlCon.Open();
// SPECIFY the column you insert into!
// Without the # "query" is not recognized as a multiline string... that's why the PO is getting that VALUES does not exists in the current context...
string query = #"INSERT INTO Employee (ID, Name, City, Address)
VALUES (#ID, #Name, #City, #Address)";
for (int i = 0; i <= 100; i++)
{
SqlCommand sqlcmd = new SqlCommand(query, sqlCon);
// set the individual parameters, and AVOID "AddWithValue"
sqlcmd.Parameters.Add("#ID", SqlDbType.Int).Value = i;
sqlcmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = "newride";
sqlcmd.Parameters.Add("#City", SqlDbType.VarChar, 100).Value = "newride";
sqlcmd.Parameters.Add("#Address", SqlDbType.VarChar, 100).Value = "USA";
// and then *EXECUTE* the SqlCommand to actually RUN the INSERT
sqlcmd.ExecuteNonQuery();
}
}

Query for instance_name, port number in format in SQL Server

I need result in below format, with current connection port. Can someone help me?
servername\instance,3000
Thanks
The following shows you code you can run as c# Console app to get what you want. If you are already in SQL Management Studio, then you just need to execute the commands directly:
static void Main(string[] args)
{
using (var conn = new SqlConnection("Integrated Security=true; Initial Catalog=dbname;Data Source=servername"))
{
using (var cmd = new SqlCommand("SELECT SERVERPROPERTY('ServerName'), SERVERPROPERTY('InstanceName')", conn))
{
string serverName = "";
string instanceName = "";
cmd.CommandType = System.Data.CommandType.Text;
conn.Open();
var rdr = cmd.ExecuteReader();
if (rdr.Read())
{
serverName = rdr.GetString(0);
if (!rdr.IsDBNull(1))
{
instanceName = rdr.GetString(1);
}
}
rdr.Close();
Console.WriteLine("Server name of this connection is: " + serverName + ". Instance of this connection is: " + instanceName);
}
using (var cmd = new SqlCommand("xp_readerrorlog", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
var param = cmd.CreateParameter();
param.ParameterName = "#ArchiveID";
param.DbType = System.Data.DbType.Int32;
param.Value = 0;
cmd.Parameters.Add(param);
param = cmd.CreateParameter();
param.ParameterName = "#LogType";
param.DbType = System.Data.DbType.Int32;
param.Value = 1;
cmd.Parameters.Add(param);
param = cmd.CreateParameter();
param.ParameterName = "#Filter1Text";
param.DbType = System.Data.DbType.String;
param.Value = "Server is listening on";
cmd.Parameters.Add(param);
var rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr.GetString(2));
}
rdr.Close();
}
}
Console.ReadKey();
}
Note that if your server is using default instance (as mine does) then instance name is NULL.

Wrong Format of the initialization string in ADO.NET

I just have a simply method show below:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string sqlcmdString = string.Format("UPDATE Bills SET Name = '#name', Time = '#time', Product = '#pro', Price = #money WHERE Name = '#value';");
using (SqlConnection con = new SqlConnection(sqlcmdString))
using (SqlCommand cmd = new SqlCommand("dbo.Bills", con))
{
// tell ADO.NET it's a stored procedure (not inline SQL statements)
cmd.CommandType = CommandType.StoredProcedure;
// define parameters
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 100).Value = tb_TenKH.Text;
cmd.Parameters.Add("#time", SqlDbType.DateTime).Value = cb_Thoigian.Text;
cmd.Parameters.Add("#pro", SqlDbType.NVarChar, 100).Value = tb_SanPham.Text;
cmd.Parameters.Add("#money", SqlDbType.Money).Value = tb_ThanhTien.Text;
cmd.Parameters.Add("#value", SqlDbType.NVarChar, 100).Value = cellvalue;
// open connection, execute stored procedure, close connection again
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
//dosomething
}
else
{
MessageBox.Show("Failed!!!");
}
con.Close();
}
}
This lines could not be run. When i debug it, it shows error:
System.ArgumentException: 'Format of the initialization string does
not conform to specification starting at index 0.'
I aware that something went wrong in my sqlcmdString maybe about syntax, but I couldn't determine it. Please give me a help.
I'm wrong in syntax: I should use like below:
string sqlcmdString = string.Format("UPDATE Bills SET Name = '#name', Time = '#time', Product = '#pro', Price = #money WHERE Name = '#value';");
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sqlcmdString, con))
{
cmd.CommandType = CommandType.Text;
// define parameters
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 100).Value = tb_TenKH.Text;
cmd.Parameters.Add("#time", SqlDbType.DateTime).Value = cb_Thoigian.Text;
cmd.Parameters.Add("#pro", SqlDbType.NVarChar, 100).Value = tb_SanPham.Text;
cmd.Parameters.Add("#money", SqlDbType.Money).Value = tb_ThanhTien.Text;
cmd.Parameters.Add("#value", SqlDbType.NVarChar, 100).Value = cellvalue;
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Thành Công!!!");
if (passrow != null)
{
string[] result_back = { tb_TenKH.Text, cb_Thoigian.Text, tb_SanPham.Text, tb_ThanhTien.Text };
passrow(result_back);
{
this.Hide();
}
}
}
else
{
MessageBox.Show("Thất Bại!!!");
}
con.Close();
}
}

SQL Server database won't update new information

I don't understand it. This code should work, but there must be something I've done wrong.
Can anyone see what I've done wrong?
string username = tbNewUSER.Text.Trim();
string password = tbNewPass.Text.Trim();
string role = "USER";
string str = "insert into UserValidation (USERNAME, PASSWORD, ROLE) values ('" + username + "','" + password + "','" + role + "')";
MessageBox.Show(username + " Registered", "User registration",MessageBoxButtons.OK, MessageBoxIcon.Information);
clsDB.InsUpDel(str);
And this is the follow up:
public static int InsUpDel(string str)
{
if (!(conn.State == ConnectionState.Open))
conn.Open(); //open connection if closed
int numRows = 0; //counter that checks number of rows affected in the db
try
{
SqlCommand cmd = new SqlCommand(str, conn);
numRows = cmd.ExecuteNonQuery();
cmd = null;
}
catch (SqlException ex)
{
string errorMsg = ex.Message; //more code can be put here
}
if (conn.State == ConnectionState.Open)
conn.Close();
return numRows;
}
Thank you.
Side notes:
Always use parameters for your queries and never string concatenation. For fun see Bobby Tables
Do not use static, there are not many places you need this.
Dont share database connections, create them and destroy them as needed.
Do not store passwords as plain text ever!
Do not catch exceptions you do not plan to handle. Log them and rethrow (using throw;) or do not catch at all. This last one will help you figure out why "its not working"
Updated code
public void UpdateUser() {
var userModel = new UserModel {
Username = tbNewUSER.Text.Trim(),
Password = tbNewPass.Text.Trim(),
Role = "USER"
};
var result = UpdateUser(userModel);
}
public int UpdateUser(UserModel user)
{
const string str = "insert into UserValidation (USERNAME, PASSWORD, ROLE) values (#userName, #password, #role)";
using(var conn = new SqlConnection("your connection string here, hint best to get it from the app.config"))
using(var command = new SqlCommand(str, conn))
{
command.Parameters.Add(new SqlParameter("#userName", SqlDbType.VarChar, 255) {Value = user.UserName});
command.Parameters.Add(new SqlParameter("#password", SqlDbType.VarChar, 255) {Value = user.Password});
command.Parameters.Add(new SqlParameter("#role", SqlDbType.VarChar, 255) {Value = user.Role});
conn.Open();
return cmd.ExecuteNonQuery();
}
}
UserModel.cs
public class UserModel {
public string UserName {get;set;}
public string Password {get;set;}
public string Role {get;set;}
}

Resources