I'm trying to all the sql function from the c#.
I've had added the parameters to the function as # fileid and useid. But getting an error. I couldn't figure out the bug in my code..
string query = "exec fn_sh_HitInfo(#fileid,#UserID)";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#fileid", SqlDbType.BigInt).Value=fid;
cmd.Parameters.Add("#UserID", SqlDbType.BigInt).Value =UserID;
string taglist = string.Empty;
try
{
taglist = DBAction.ExecuteQuery(cmd, FilteringControl.ProjectID).ToString();
}
Don't use parentheses
exec fn_sh_GetTagListHitInfo #fileid,#UserID
Or if this is a scalar UDF you can alternatively use SELECT instead of EXEC (requires schema name in this case)
SELECT dbo.fn_sh_GetTagListHitInfo (#fileid,#UserID )
You don't need the exec part and you don't need to know the correct syntax.
//string query = "exec fn_sh_GetTagListHitInfo(#fileid,#UserID)";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure; // just mark it as an SP
cmd.CommandText = "fn_sh_GetTagListHitInfo"; // only the name
cmd.Parameters.Add("#fileid", SqlDbType.BigInt).Value=fid;
cmd.Parameters.Add("#UserID", SqlDbType.BigInt).Value = FilteringControl.UserID;
Change the cmd.CommandText value and try.
cmd.CommandText = "select fn_sh_GetTagListHitInfo(#fileid,#UserID)";
Related
I have a example: I am using C# to solve Oracle database problem
cmd = new OracleCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select DATE_START from EMPLOYEE;";
It works successfull.
BUt when I use GROUP BY, it doesm't work.
cmd = new OracleCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select DATE_START from EMPLOYEE GROUP BY DATE_START;";
It doesn't work
ORA-00911: invalid character.
Thanks so much
Try removing the semicolon(;) from CommandText like
cmd.CommandText = "select DATE_START from EMPLOYEE GROUP BY DATE_START";
//^^ From Here
I am not sure why it should be a problem, but I have seen similar issue before with Oracle + ADO.Net.
Also, if you are not using any aggregate methods then you can use DISTINCT keyword instead of GROUP BY like:
cmd.CommandText = "SELECT DISTINCT DATE_START from EMPLOYEE";
using this coding,while i give fruitId ,i need to retrieve fruitname,using this it shows some error..any one help...
string constring = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("savefruit11", con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FruitsId", int.Parse(TextBox3.Text.Trim()));
cmd.Parameters.Add("#Fruitsname", SqlDbType.VarChar, 50);
cmd.Parameters["#Fruitsname"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
con.Close();
TextBox4.Text = "Fruit Name:"+cmd.Parameters["#FruitName"].Value.ToString();
}
}
Store procedure for the above code.
use[FruitsDB]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[savefruit11]
#FruitId INT,
#FruitName VARCHAR(50) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT #FruitName = Fruitsname
FROM Fruits1
WHERE FruitsId = #FruitId
END
cmd.Parameters.Add("#Fruitsname", SqlDbType.VarChar, 50);
cmd.Parameters["#Fruitsname"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
con.Close();
TextBox4.Text = "Fruit Name:"+cmd.Parameters["#FruitName"].Value.ToString();
Your parameter is called #Fruitsname, but you get it back with #FruitName. You have an additional s in the first version. Make them consistent by changing the first #FruitsName to #FruitName which will match what you have in the stored procedure.
Or, as Henk suggested in the comments create a const string to contain your parameter name so that it is consistent across all usages.
Use cmd.ExecuteQuery or cmd.ExecuteScalar
//To Execute SELECT Statement
ExecuteQuery()
//To Execute Other Than Select Statement(means to Execute INSERT/UPDATE/DELETE)
ExecuteNonQuery()
with your udpate
s is missing in parameter name in stored procedure
Use the following example way
using (SqlConnection connection = new SqlConnection())
{
string connectionStringName = this.DataWorkspace.AdventureWorksData.Details.Name;
connection.ConnectionString =
ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
string procedure = "HumanResources.uspUpdateEmployeePersonalInfo";
using (SqlCommand command = new SqlCommand(procedure, connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(
new SqlParameter("#EmployeeID", entity.EmployeeID));
command.Parameters.Add(
new SqlParameter("#NationalIDNumber", entity.NationalIDNumber));
command.Parameters.Add(
new SqlParameter("#BirthDate", entity.BirthDate));
command.Parameters.Add(
new SqlParameter("#MaritalStatus", entity.MaritalStatus));
command.Parameters.Add(
new SqlParameter("#Gender", entity.Gender));
connection.Open();
command.ExecuteNonQuery();
}
}
reference from MSDN
http://msdn.microsoft.com/en-us/library/jj635144.aspx
I run this code:
SqlConnection polaczenie;
polaczenie = new SqlConnection(dane_polaczenia);
SqlCommand cmd = new SqlCommand();
cmd.Connection = polaczenie;
polaczenie.Open();
cmd.CommandText = #"SELECT * FROM test.test";
cmd.ExecuteNonQuery();
After executing I got exception Invalid object name 'test.test'.
Database and table values are correct.
How to specify database.table in CommandText correctly?
cmd.CommandText = #"SELECT * FROM test.dbo.test";
or
cmd.CommandText = #"SELECT * FROM test..test";
I have a simple SQL Server stored procedure:
ALTER PROCEDURE GetRowCount
(
#count int=0 OUTPUT
)
AS
Select * from Emp where age>30;
SET #count=##ROWCOUNT;
RETURN
I am trying to access the output parameter in the following C# code:
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=answers;Integrated Security=True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "GetRowCount";
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#count", SqlDbType.Int));
cmd.Parameters["#count"].Direction = ParameterDirection.Output;
con.Open();
SqlDataReader reader=cmd.ExecuteReader();
int ans = (int)cmd.Parameters["#count"].Value;
Console.WriteLine(ans);
But on running the code, a NullReferenceException is being thrown at the second last line of the code. Where am I going wrong? Thanks in advance!
P.S. I am new to SQL Procedures, so I referred this article.
I'd suggest you put your SqlConnection and SqlCommand into using blocks so that their proper disposal is guaranteed.
Also, if I'm not mistaken, the output parameters are only available after you've completely read the resulting data set that's being returned.
Since you don't seem to need that at all - why not just use .ExecuteNonQuery() instead? Does that fix the problem?
using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=answers;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand("dbo.GetRowCount", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#count", SqlDbType.Int));
cmd.Parameters["#count"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery(); // *** since you don't need the returned data - just call ExecuteNonQuery
int ans = (int)cmd.Parameters["#count"].Value;
con.Close();
Console.WriteLine(ans);
}
Also : since it seems you're only really interested in the row count - why not simplify your stored procedure to something like this:
ALTER PROCEDURE GetRowCount
AS
SELECT COUNT(*) FROM Emp WHERE age > 30;
and then use this snippet in your C# code:
con.Open();
object result = cmd.ExecuteScalar();
if(result != null)
{
int ans = Convert.ToInt32(result);
}
con.Close();
you have to specify that it is a stored procedure not a query
cmd.CommandType = CommandType.StoredProcedure;
Just use ExecuteNonQuery , you can't use ExecuteReader with out parameter in this case
cmd.ExecuteNonQuery();
Or if you want try with ExecuteScalar and ReturnValue
You should add
cmd.CommandType = CommandType.StoredProcedure
before calling it
I find the problem, its the connection string.
But now, in the code:
usuary = (string)cmd.Parameters["#USUARIO"].Value;
password = (string)cmd.Parameters["#CLAVE"].Value;
the compiler infomrs thats values are null...
I want to know how to execute more than one SQL command at once.
At this moment I'm doing it like this:
using (SqlConnection sqlConnection1 = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT nome FROM teste";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
// execute the command
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
listBox1.Items.Add(rdr["name"].ToString());
}
}
}
But how can I do to execute
use [databaseX]
SELECT nome FROM teste
in my c# program?
Separate multiple statements with a semicolon (;).
(BTW, the use statement is generally not needed because it's set in your connection string.)
Use # to declare the string:
cmd.CommandText = #"
use [databaseX]
SELECT nome FROM teste
";
OR actually escape the line break:
cmd.CommandText = "use [databaseX]\nSELECT nome FROM teste";
SQL uses a ; to seperate commands / queries.
SELECT * FROM Table1; SELECT * FROM Table2;
results in to result sets.