ADO.NET + T-SQL Invoke scalar function from another DB? - c#

I have an SQL script select [master].[dbo].sp_SearchDuplicatedAddress('','','','') that I can invoke successfully from management studio. The function sp_SearchDuplicatedAddress exists in master database and is accessible by the logged user, no problem here. The problem arises when I try to execute that SQL script from ADO.Net I get the following error:
System.Data.SqlClient.SqlException: 'Cannot find either column "master" or the user-defined function or aggregate "master.dbo.sp_SearchDuplicatedAddress", or the name is ambiguous.'
And here's the code of sample app:
var conn = new SqlConnection();
var cmd = conn.CreateCommand();
cmd.CommandText = "select [master].[dbo].sp_SearchDuplicatedAddress('','','','')";
conn.Open();
var outt = cmd.ExecuteScalar();
}
Any idea how can I execute cross database queries from ADO.Net?

No repro for me. Can you modify the below to reproduce the behavior?
using Microsoft.Data.SqlClient;
using System;
namespace SqlClientTest
{
class Program
{
static void Main(string[] args)
{
var constr = "server=localhost;database=master;integrated security=true";
using (var conn = new SqlConnection(constr))
{
var cmd = conn.CreateCommand();
cmd.CommandText = #"
create or alter function dbo.sp_SearchDuplicatedAddress ( #a varchar(20),#b varchar(20),#c varchar(20),#d varchar(20) )
returns int
as
begin
return 3;
end ";
conn.Open();
cmd.ExecuteNonQuery();
}
constr = "server=localhost;database=tempdb;integrated security=true";
using (var conn = new SqlConnection(constr))
{
var cmd = conn.CreateCommand();
cmd.CommandText = "select [master].[dbo].sp_SearchDuplicatedAddress('','','','')";
conn.Open();
var outt = cmd.ExecuteScalar();
Console.WriteLine(outt);
}
}
}
}

Related

Insert data to Excel table using OLEDb

My code looks like
using System.Data.OleDb;
namespace ConsoleApplication21
{
class Program
{
static void Main(string[] args)
{
string constr2 = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\productivity\temp.xlsx;Extended Properties='Excel 8.0;HDR=no'";
OleDbConnection conn = new OleDbConnection(constr2);
conn.Open();
OleDbCommand INSERTcommand = new OleDbCommand();
INSERTcommand.Connection = conn;
INSERTcommand.CommandText = "create table [table3] (id INT, name VARCHAR, datecol DATE);";
INSERTcommand.ExecuteNonQuery();
OleDbCommand INSERTDATA = new OleDbCommand();
INSERTDATA.Connection = conn;
INSERTDATA.CommandText = "INSERT INTO [table3] (id,name,datecol) values (1,'aaaa','25-01-2012');";
INSERTDATA.ExecuteNonQuery();
}
}
}
After executing the above code an exception shows:
The INSERT INTO statement contains the following unknown field name:
'id'. Make sure you have typed the name correctly, and try the
operation again.
if you omit the column specifications while inserting, it works fine:
INSERTDATA.CommandText = "INSERT INTO [table3] values (1,'aaaa','25-01-2012');";

If record exists dont insert

I'm trying something out but cant figure it out. So what i'm trying is that if the user inputs something inside txtISN and it already exists inside of the database, the record wont be inserted. I also want a error msg to pop up when a record wasnt inserted and when a record is inserted I want an message to pop up saying that the record was inserted succesfully.
Thanks for the help y'all!
string _connStr = #"Data Source = EJQ7FRN; Initial Catalog = BES; Integrated Security = True";
string _query = "INSERT INTO [BES_S] (ISN,Titel,Name) values (#ISN,#Titel,#Name)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("#ISN", txtISN.Text);
comm.Parameters.AddWithValue("#Titel",txtTitel.Text);
comm.Parameters.AddWithValue("#Name", txtName.Text);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch (SqlException ex)
{
}
}
}
You need to change your query a bit, but you can use MySql's DUAL keyword to do this:
string _connStr = #"Data Source = EJQ7FRN; Initial Catalog = BES; Integrated Security = True";
string _query = "INSERT INTO [BES_S] (ISN,Titel,Name) ";
_query = _query + " SELECT #ISN, #Titel, #Name FROM DUAL";
_query = _query + " WHERE NOT EXISTS (SELECT ISN WHERE ISN=#ISN)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("#ISN", txtISN.Text);
comm.Parameters.AddWithValue("#Titel",txtTitel.Text);
comm.Parameters.AddWithValue("#Name", txtName.Text);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch (SqlException ex)
{
}
}
}
DUAL is like a dummy table that you can use to SELECT from.
Let the database take care of this using a unique constraint/index:
alter table bes_s add constraint unq_bes_ISN unique (ISN);
This will cause the database to generate an error if a duplicate ISN is inserted. You can put one or more columns for the unique constraint (in case this single column is not the exact definition of uniqueness).

sql server retrieve and update (windows phone 7)

I have a retrieve code of:
[WebMethod]
public List<Hawker> retrievehawker()
{
List<Hawker> retrievehawker = new List<Hawker>();
string qry = #"select hawkername, address, postal, xcoord, ycoord, popularity from uploadphoto";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = qry;
conn.Open();
SqlDataReader mySqlDataReader = cmd.ExecuteReader();
while (mySqlDataReader.Read())
{
Hawker retrieveHawker = new Hawker();
retrieveHawker.hawkername = Convert.ToString(mySqlDataReader["hawkername"]);
retrieveHawker.address = Convert.ToString(mySqlDataReader["address"]);
retrieveHawker.postal = Convert.ToString(mySqlDataReader["postal"]);
retrieveHawker.xcoord = Convert.ToDouble(mySqlDataReader["xcoord"]);
retrieveHawker.ycoord = Convert.ToDouble(mySqlDataReader["ycoord"]);
retrieveHawker.popularity = Convert.ToDouble(mySqlDataReader["popularity"]);
retrievehawker.Add(retrieveHawker);
}
mySqlDataReader.Close();
conn.Close();
return retrievehawker;
}
and a setpopularity of :
[WebMethod]
public int SetPopularity()
{
string qry = #"update uploadphoto set popularity=popularity+1";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = qry;
conn.Open();
int status = cmd.ExecuteNonQuery();
conn.Close();
return status;
}
How can I combine them together so that based on a selection of a place in the windows phone 7, of a button click, then it will trigger the setpopularity. Right now the code for set popularity is adding the whole column of +1 to popularity. Help please.
You need to pass to your SetPopularity method the primary key (or another unique value) of your photo table.
In that way you could change your sql command to update only the record required
[WebMethod]
public int SetPopularity(string hawkername)
{
string qry = #"update uploadphoto set popularity=popularity+1
WHERE hawkername=#hawk";
using(SqlConnection conn = new SqlConnection(connString))
using(SqlCommand cmd = new SqlCommand(qry, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#hawk", hawkername);
int status = cmd.ExecuteNonQuery();
return status;
}
}
The string passed to the method is your primary key (or an unique value better if indexed) and could be used in the WHERE clause.
Notice also the using statement around the disposable objects and the parameterized query approach to avoid Sql Injections and parsing problems.

Executing SQl Queries in C# using CLR

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;
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();
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).
To connect with the database you have to mention the database username and password in the connection string of your web.config file.

connecting to sql database c# asp.net

hallo there
This is a very basic question. I am currently a student and have done ASP.NET with C#.
For our purposes it was required to do work with an access database where connecting to it and adding data etc.was very easy.
My feeling is that access is not used much in the real world and would just like to enquire on the easiest and most correct way of establishing a connection to Microsoft Sql Server Database(Transact sql).
In my case the database is called dbActivities with primary data file being dbActivitiesData.mdf.
OleDbDataConnection conn;
conn = new OleDbConnection = #"Provider=Microsoft.Jet.Oledb.4.0:"
#"Data Source=DataBase.mdb";
conn.Open();
Regards
My feeling is that access is not used much in the real world
Unfortunately Access is still very much used in the real world :-)
As far as the correct way is concerned I would recommend you wrapping the connection into a using block to ensure proper handling:
class Program
{
static void Main()
{
var connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\work\DataBase.mdb";
using (var conn = new OleDbConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Name FROM Customers";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var customerName = reader.GetString(reader.GetOrdinal("Name"));
Console.WriteLine(customerName);
}
}
}
}
}
And as far as Microsoft SQL Server is concerned:
var connectionString = #"Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";
using (var conn = new SqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Name FROM Customers";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var customerName = reader.GetString(reader.GetOrdinal("Name"));
Console.WriteLine(customerName);
}
}
}
string strSQLCommand;
SqlCommand command;
SqlConnection conn = null;
conn =new SqlConnection("Data Source=serverName\IP;Initial Catalog=dbActivities;UID=User;PWD=Password;Max Pool Size=500;");
strSQLCommand = "Your Command";
command = new SqlCommand(strSQLCommand, conn);
command.ExecuteNonQuery();
conn.Close();

Categories