Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi.
I'm replacing my old column values with new column values but my query is not executed and sometime give me error "invalid 'tbl_field' " but tbl_field is present,tbl_field is my table name.How can i resolve this issue.

What I have tried:

Here is my code aspx.cs
C#
public void updateTbl(string newname)
    {
        string oldname = Session["oldname"].ToString();
        String db = Session["value"].ToString();
        SqlConnection cnn = new SqlConnection("Data Source=HAMEED_KHAN\\SQLEXPRESS; Initial catalog=db_compiler; Integrated security=true");
        string RNquery="USE "+db+" EXEC sp_rename '"+oldname+"', '"+newname+"'";
        string updateQuery = "USE "+db+" Update 'tbl_field' SET Table_Name= replace(Table_Name, "+ oldname + ", " + newname + ")";
        SqlCommand cmd2 = new SqlCommand(updateQuery, cnn);
        SqlCommand cmd = new SqlCommand(RNquery, cnn);
        cnn.Open();
        cmd2.ExecuteNonQuery();//Here ERROR 'incorrect syntax near tbl_field
        cmd.ExecuteNonQuery();
       
        cnn.Close();
    }

My 'RNquery' which is used to change table name in database working fine but issue with 'updateQuery' its give my error but when i execute this query in sql ,it's working fine,i think there is some little mistake with ',or " etc.Thanks
Posted
Updated 4-May-16 19:11pm
v2

SQL
Update 'tbl_field' 

I think this should be...
SQL
Update tbl_field 
 
Share this answer
 
try this

C#
string updateQuery = "USE " + db + " Update tbl_field SET Table_Name= replace(Table_Name, '" + oldname + "', '" + newname + "')";


but framing an sql statement in c# is prone to SQL injection attacks, if you are getting the input values from user, instead you should use SQL Parameters
refer these articles

SQL Injection[^]
SQL Injection Attacks and Some Tips on How to Prevent Them[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]
 
Share this answer
 
if you want to use same database and you have a connection string then why to use 'use' statement, basically it use to Changes the database context to the specified database or database snapshot in SQL Server. remove 'use' and try again
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900