C# alter stored procedure programmatically - c#

I have the following C# code that should allow me to modify (alter) a stored procedure of mine:
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConnection"].ConnectionString);
ServerConnection srvCon = new ServerConnection(sqlCon);
sqlCon.Open();
Server srv = new Server(srvCon);
Database db = srv.Databases[sqlCon.Database];
StoredProcedure sp = new StoredProcedure(db, "spRDLDataFetcher");
sp.TextMode = false;
sp.AnsiNullsStatus = false;
sp.QuotedIdentifierStatus = false;
sp.TextBody = "SELECT blah FROM MyTable WHERE ID=1";
sp.Alter();
However, the sp.Alter()call throws this error:
Microsoft.SqlServer.Management.Smo.FailedOperationException: 'Alter failed for StoredProcedure 'dbo.spRDLDataFetcher'. '
Inner Exception: InvalidSmoOperationException: You cannot perform operation Alter on an object in state Creating.
What am I missing in order to get it to alter (update) that stored procedure?

Alright so I found out why it was not updating it. Seems, for whatever reason, it needed sp.Refresh(); First before I overwrote the textBody.
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConnection"].ConnectionString);
ServerConnection srvCon = new ServerConnection(sqlCon);
sqlCon.Open();
Server srv = new Server(srvCon);
Database db = srv.Databases[sqlCon.Database];
StoredProcedure sp = new StoredProcedure(db, "spRDLDataFetcher");
sp.TextMode = false;
sp.AnsiNullsStatus = false;
sp.QuotedIdentifierStatus = true;
sp.ImplementationType = ImplementationType.TransactSql;
sp.Schema = "dbo";
sp.Refresh(); //What was needed to make work
string orgSPText = sp.TextBody;
sp.TextBody = "SELECT blah FROM MyTable WHERE ID=1";
sp.Recompile = true;
sp.Alter();
The sp.Recompile = true; really is not needed. It will work without it but I like to keep that in there just for kicks and giggles.

Related

selecting non-english character using oracle client in c#

I'm trying execute query in C# to store the data in DataTable. however the database has some non-English character(AR8MSWIN1256). the result of the select query returns (????)
my code :
System.Data.OracleClient.OracleConnection con = new System.Data.OracleClient.OracleConnection();
System.Data.OracleClient.OracleConnectionStringBuilder ocsb = new System.Data.OracleClient.OracleConnectionStringBuilder();
ocsb.Password = "password";
ocsb.UserID = "username";
ocsb.DataSource = "datasource";
ocsb.Unicode = true;
System.Data.OracleClient.OracleCommand cmd = new System.Data.OracleClient.OracleCommand(
"SELECT 'ب' LETTER FROM DUAL", con);
Console.WriteLine(cmd.ExecuteScalar().ToString());
the result is (?)
can anyone help with this issue. thank you

How to fix 'When I write the stored procedure for searching'?

I'm writing a stored procedure for searching in many records and nothing wrong but the problem is when I search for a record and need to update this record after search gave me this exception and when I go to record without search I can update it. Is this a problem in C# or in the stored procedure?
private void button2_Click(object sender, EventArgs e)
{
frm.dtpCheck.Text = this.dataGridView1.CurrentRow.Cells[9].Value.ToString();
frm.dtpnextCheck.Text = this.dataGridView1.CurrentRow.Cells[10].Value.ToString();
frm.txtIncomMoney.Text = this.dataGridView1.CurrentRow.Cells[11].Value.ToString();
frm.txtResMoney.Text = this.dataGridView1.CurrentRow.Cells[12].Value.ToString();
frm.txtfrom.Text = this.dataGridView1.CurrentRow.Cells[13].Value.ToString();
frm.txtto.Text = this.dataGridView1.CurrentRow.Cells[14].Value.ToString();
frm.Text = "Update Patient" + this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
frm.btnOk.Text = "Update";
ALTER proc [dbo].[Search_Pa]
#ID nvarchar(50)
as
select * from tb_Patients
inner join tb_Rolls
on tb_Patients.RollID =tb_Rolls.RollID
where tb_Patients.PatientName+
tb_Patients.PatientAddress+
tb_Patients.PatientPhone
like '%'+#ID+'%'
param[7] = new SqlParameter("#dateofcheck", SqlDbType.DateTime2);
param[7].Value = DateOfCheck;
param[8] = new SqlParameter("#dateofnextcheck", SqlDbType.DateTime2);
param[8].Value = DateOfNextCheck;
param[9] = new SqlParameter("#residualmoney", SqlDbType.Decimal);
param[9].Value = ResidualMoney;
param[10] = new SqlParameter("#receivemoney", SqlDbType.Decimal);
param[10].Value = IncomingMoney;
param[11] = new SqlParameter("#firstcheck", SqlDbType.VarChar,10);
param[11].Value = FirstCeck;
param[12] = new SqlParameter("#endcheck", SqlDbType.VarChar,10);
param[12].Value = EndCheck;
param[13] = new SqlParameter("#ID", SqlDbType.Int);
param[13].Value = ID;
param[14] = new SqlParameter("#RID", SqlDbType.Int);
param[14].Value = RID;
dal.IUD("update_Patients", param);
dal.CloseCon();
}
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: String was not recognized as a valid DateTime.) in Cells[9]

Why cannot I see in IBM Data Studio a temporary table created by an application?

I am using the code below to connect to an IBM DB2 database and perform Bulkcopy. After it executes CMD.EXECUTENONQUERY() method, I try to verify whether the table is created or not in the IBM Data Studio client interface, but it says "Table name undefined". Can someone explain why I cannot see the table?
public void ExecuteBulkCopy(string connectionString, DataTable source, string destinationTableName,
int timeOut)
{
var schema = "DEVPROC";
var procName = $"{schema}.FSVPTEMP001";
var commandText =
"declare global temporary table TEMP_TRY_NEW(CPK_ID CHAR(25), VDR_ID INTEGER,P_ID CHAR(15),MPP_CPK_K_ID DECIMAL(12),MPP_P_K_ID DECIMAL(12),ODBMS_VDR_KEY_ID DECIMAL(12),DEL_ELIG_DT DATE,RW_CRT_TS TIMESTAMP,RW_CRT_PRC_ID CHAR(11),RW_UDT_TS TIMESTAMP,RW_UDT_PRC_ID CHAR(11))ON COMMIT PRESERVE ROWS;";
var connection = new DB2Connection(connectionString);
{
var cmd = new DB2Command(commandText, connection);
{
connection.Open();
cmd.ExecuteNonQuery();
var copy = new DB2BulkCopy(connection);
copy.DestinationTableName = destinationTableName;
copy.BulkCopyTimeout = timeOut;
copy.WriteToServer(source);
copy.Close();
connection.Close();
}
}
}

Stored procedure returns no rows with SqlDataAdapter

I'm new to using SqlDataAdpter and I'm trying to execute a stored procedure. The stored procedure executes successfully but no rows are returned. I've used SQL Server Profiler to monitor the call and it runs successfully (I can copy and execute the query from profiler without modifying it and get results).
I have the following:
public ActionResult Index()
{
SqlConnection conn = null;
DataSet results = null;
try
{
string connectionString = // ... my connection
conn = new SqlConnection(connectionString );
string query = #"usp_mySP";
conn.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter(query, conn);
sqlAdpt.SelectCommand.CommandType = CommandType.StoredProcedure;
var dataDate = new SqlParameter { ParameterName = "#DataDate", Value = DateTime.Now };
var idList = new SqlParameter { ParameterName = "#IDList", Value = "1231,2324,0833" };
sqlAdpt.SelectCommand.Parameters.Add(dataDate);
sqlAdpt.SelectCommand.Parameters.Add(idList);
results = new DataSet();
sqlAdpt.Fill(results);
sqlAdpt.Dispose();
}
catch (SqlException e)
{
throw new Exception("Exception:" + e.Message);
}
finally
{
if (conn != null)
conn.Close();
}
return View(results);
}
When I inspect the DataSet through the debugger, it always returns 0 rows.
Please help with what I'm doing wrong?
Note: I've also tried (but do NOT prefer) executing as a SQL command:
EXEC usp_mySP #DataDate, #IDList
and it didn't work either as I got int to varchar conversion errors.
I think you try to add SqlParameter using SqlCommand like this :
SqlCommand cmd = new SqlCommand();
cmd.parameter.addwithvalue(#DataDate,DateTime.Now);
So the reason was because of set nocount on. I added it to my sp and it works. Thank you everyone for clarifying.

Pervasive SQL System Stored Procedure from ADO.NET error

I'm just trying to return a list of columns and their attributes through a system stored procedure. What documentation I have seems to say the below code should work, but I get "Pervasive.Data.SqlClient.Lna.k: [LNA][Pervasive][ODBC Engine Interface]Invalid or missing argument." on the execute. This is PSQL v11, .NET 4.5.
using (PsqlConnection conn = new PsqlConnection(cs))
{
PsqlCommand locationCmd = new PsqlCommand();
PsqlParameter tableParam = new PsqlParameter();
PsqlParameter returnParam = new PsqlParameter();
returnParam.Direction = ParameterDirection.ReturnValue;
locationCmd.CommandText = "psp_columns";
locationCmd.Connection = conn;
locationCmd.CommandType = CommandType.StoredProcedure;
locationCmd.Parameters.Add(tableParam).Value = table;
locationCmd.Parameters.Add(returnParam);
conn.Open();
locationCmd.ExecuteNonQuery();
}
I would think the problem is this line:
locationCmd.Parameters.Add(tableParam).Value = table;
You should set the value before adding the parameter, not afterwards.
tableParam.Value = table;
locationCmd.Parameters.Add(tableParam);
I don't know about Psql but for MSSQL normally you also need to define the parameter name as its found in the stored procedure, or at least that's what I do.
SqlParameter param = new SqlParameter("#tableParam", value);
The psp_Columns system stored procedure is defined as call psp_columns(['database_qualifier'],'table_name', ['column_name']). I know that it says the database qualifier is optional, but I think it's required. You could try passing an empty string for the qualifier. Something like:
using (PsqlConnection conn = new PsqlConnection(cs))
{
PsqlCommand locationCmd = new PsqlCommand();
PsqlParameter dbParam = new PsqlParameter();
PsqlParameter tableParam = new PsqlParameter();
PsqlParameter returnParam = new PsqlParameter();
returnParam.Direction = ParameterDirection.ReturnValue;
locationCmd.CommandText = "psp_columns";
locationCmd.Connection = conn;
locationCmd.CommandType = CommandType.StoredProcedure;
locationCmd.Parameters.Add(dbParam).Value = ""; //might need two single quotes ('')
locationCmd.Parameters.Add(tableParam).Value = table;
locationCmd.Parameters.Add(returnParam);
conn.Open();
locationCmd.ExecuteNonQuery();
}
You should try to get the information of the table SCHEMA using the provided GetSchema method from the Psqlconnection. I have searched a bit on their support site and it seems that this method is supported although I haven't find a direct example using the Tables collection.
This is just an example adapted from a test on mine on SqlServer, I don't have Pervasive install, but you could try if the results are the same
using(PsqlConnection cn = new PsqlConnection("your connection string here"))
{
cn.Open();
string[] selection = new string[] { null, null, table };
DataTable tbl = cn.GetSchema("Columns", selection);
foreach (DataRow row in tbl.Rows)
{
Console.WriteLine(row["COLUMN_NAME"].ToString() + " " +
row["IS_NULLABLE"].ToString() + " " +
row["DATA_TYPE"].ToString()
);
}
}
i was trying to figure this out as well, but with the tables procedure. even though the database and table names are optional, you still have to provide values. for optional parameters, pass in DBNull.Value
this worked for me:
PsqlCommand cm = new PsqlCommand();
cm.CommandText = "psp_tables";
cm.CommandType = CommandType.StoredProcedure;
cm.Connection = new PsqlConnection();
cm.Connection.ConnectionString = <your connection string>;
cm.Parameters.Add(":database_qualifier", DBNull.Value);
cm.Parameters.Add(":table_name", DBNull.Value);
cm.Parameters.Add(":table_type", "User table");

Categories