Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to write a C# application to check the selected stored procedure for some criteria. For example if the stored procedure contains 5 select queries the same query must contais 5 with(nolock) (select for temp tables except).
How can I do this via C#? Thanks in advance.
You can use sys.objects to query SQL Server's metadata in order to analyze SP's definition like a text. In your case you can create query such a listed below and check its results from C# app:
SELECT object_definition(object_id) as [sp definition]
, schema_name(schema_id) [schema]
, name
, type_desc
FROM sys.objects
where object_definition(object_id) like '%select%select%select%'
and type_desc = 'SQL_STORED_PROCEDURE'
OR
SELECT object_definition(object_id) as [sp definition]
, schema_name(schema_id) [schema]
, name
, type_desc
FROM sys.objects
where object_definition(object_id) like '%NOLOCK%'
and type_desc = 'SQL_STORED_PROCEDURE'
Not sure what the question is.
You obviously need to parse the SQL (because NOLOCK can also be in a comment).
And to get the source of a stored procedure - well, use something like
using (SqlConnection sqlConnection = new SqlConnection())
{
sqlConnection.ConnectionString = yourConnectionStringHere;
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("sys.sp_helptext", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.AddWithValue("#objname", "stored_proc_name_here");
DataSet ds = new DataSet();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlCommand;
sqlDataAdapter.Fill(ds);
return DataTableToString(ds.Tables[0]);;
}
although I would never touch the sql server because I keep the source outside in version control, so a Visual Studio plug in would be the better solution.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a gridview of a SQL table. The first two columns automatically get selected and put into the grid when the webpage starts and a date is selected. The third column is a comment section where I'd like to let the user input comments themselves. I have a text box that they can enter comments in when they select a row, but I can get the column to update properly.
Run_DB_Script("update Log_Transfers set Comment = '" + tmpBox.Text + "' where '" + GridView1.Rows[Row] + "'", ref tmpErr);
The bracketed [Row] is a int that is set to the row number they put in.
It executes the code, but nothing is there after hitting update.
Building a SQL statement using the input from a user is opening the door for a SQL Injection hack. A better alternative is to use parameters.
// set up the sql command to run with parameter placeholders
// parameters are prefixed with an #
var command_text = "update Log_Transfers set Comment = #comment where #grid_row";
// Define the two parameters
SqlParameter comment = new SqlParameter("#comment",tmpBox.Text);
SqlParameter grid_row = new SqlParameter("#grid_row", ....);
SqlCommand cmd = new SqlCommand();
cmd.Text = command_text;
// Add the parameters to the command
cmd.Parameters.Add(comment);
cmd.Parameters.Add(grid_row);
cmd.Execute();
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Performance comparison between a stored procedures and simple SQL queries in C# OR linq queries.
CREATE PROCEDURE [dbo].[GetProductCM]
AS
BEGIN
SET NOCOUNT ON
SELECT
p.ProductId,
p.ProductName,
p.CategoryId
FROM
dbo.Product p
END
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "SELECT p.ProductId, p.ProductName, p.CategoryI FROM dbo.Product p";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
Product.ProductName= oReader["ProductName"].ToString();
Product.CategoryI = oReader["CategoryI "].ToString();
}
myConnection.Close();
}
}
var queryAllProduct = from p in Product
select p;
What is the best practice?
To not use a stored procedure.
The performance benefit of precompiled stored procedures was eliminated with SQL Server 7 (yes, that is 7 - 25 years or so ago, IIRC). Since then plans are cached and reused for dynamic SQL. Now stored procedures make only sense if
The SQL is VERY large and he result very slow (reducing network traffic) and the network is slow.
You do complex processing that requires brutal data transfers otherwise.
In fact, in your particular case I would use an ORM and LINQ and not waste my time manually writing SQL code (that easily accounts for 40% of a programs code) that can instead be generated.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I did my homework prior to asking this questions. Though, none of the results that google showed functioned .
I have a textbox whose input I wish to validate against a list of values which exist in a column of a table (ASP.NET with C# and SQL Server 2014 Express) . Should user enter some other value, than the error must be displayed.
I have done multiple tryouts with CustomValidator control and one when an event on the Textbox (.TextChanged). But I lost something, may be in the details. Could you give me a practical solution and at best, guide towards a useful online resource to study the connection to databases from asp.net (c#)?
I am aware that I did not catch the subject.
Here is a basic rough version how you could get it done. Can also use a Stored procedure rather than direct..Wasn't sure if you meant after a button was clicked or not, but you can put this in a method and have it return true or false if its valid.
SqlConnection cnn = null;
SqlCommand cmd = null;
SqlDataAdapter sda = null;
DataTable Dt = new Datatable();
cnn = new SqlConnection(strConnectionString);
cmd = new SqlCommand("Select COLUMN FROM WHEREVER WHERE VALUE =#TextboxValue", cnn);
cnn.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#TextboxValue", SqlDbType.VarChar).Value = Textbox.Text;
sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.rows.count > 0 )
{
//MATCH FOUND
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I found people with the same problem, but none of their solutions helped me.
string checkuser = "select count(*) from Table where Username ='" + TextBox1.Text + "'";
It says "Incorrect syntax near the keyword 'Table'."
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
something about the ToString line
Is your table actually called "Table"? If so, I'd recommend choosing a different name. If you really must call it "Table", then escape it with backquotes:
select count(*) from `Table` where Username = #Username
Also, you really should not insert the raw value from your textbox into a SQL query. That makes you prone to SQL injection attacks. Instead, you should make a #Username parameter for the query and pass the value through the parameter.
If your table name is table then it is causing error because the table is use as a keyword by sql
use something like this
select count(*) from [Table] where Username = '" + TextBox1.Text + "'";
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
1st: Is there any better way to do
sqlcommand object = new sqlcommand("insert into sometable values '" + textboxes.texts "'," + somelabelvalues.text + "')" , connectiondb); //true for update,delete and everything inwhich we want to feed input data into database.
This is not safe. Is there any better way to do this because this was taught in our C# class.
All suggestions are welcome!
Use a SqlParameter
SqlCommand cmd = new SqlCommand("Select * from sometable where value = #value");
cmd.Parameters.AddWithValue("#value", "value");
Cam Bruce is correct, use SqlParameter always. However, I would like to expound on that just a bit.
First of all, you asked if there is "a better way to do this", the answer is Yes - Use parameters. There is another answer however that was addressed in the original comments, there is a different way to do this using Entity Framework. I would say that it's only better in certain situations. If this is your only SQL query in the project, then good lord please do not use Entity Framework as the overhead would be unnecessary.
You can read up on Entity Framework on MSDN
You should also definitely read up on SQL Injection Attacks
Now on to your code. As Cam stated above, use SqlParameter. He did leave out a couple good practices though on properly handing your command and connection.
It is a good practice to wrap both your SqlCommand and SqlConnection in using statements so that when you are finished with the objects, they will be disposed of.
string mySqlCommandText = "INSERT INTO some_table VALUES (#Value1, #Value2, #Value3)";
//Wrap your connection/command in using blocks
using (var conn = new SqlConnection(mySqlConnectionString))
using (var cmd = new SqlCommand(mySqlCommandText, conn))
{
//Add your values to the parameters
//This is how you avoid the SQL Injection attack
cmd.Parameters.AddWithValue("#Value1", myValue1);
cmd.Parameters.AddWithValue("#Value2", myValue2);
cmd.Parameters.AddWithValue("#Value3", myValue3);
conn.Open();
cmd.ExecuteNonQuery();
} //The cmd and conn objects are disposed of here as they are now out of scope.
Yes this way is not safe because of SQLInjection vulnerability...
as Cam Bruce said, you can use command parameters to make it safe and secure...
SqlCommand cmd = new SqlCommand("Select * from sometable where value = #value");
cmd.Parameters.AddWithValue("#Value", "value");
cmd.ExecuteNonQuery();
just that!