How to execute an ALTER TABLE query? - c#

I have an SQL table called tbl, im trying to add the columns A, B and C to it.
When i execute the command :
String addcolumns = "ALTER TABLE SqlCreatedTbl ADD A char(50) ;";
......
cmd = new SqlCommand(addcolumns, conn);
conn.Open();
cmd.ExecuteNonQuery();
The column is added !
However, when i try to add multiple columns, it does NOT work, it gives me an error..
the command im writting for adding multiple columns is the following:
addcolumns = "ALTER TABLE SqlCreatedTbl ADD ( A char(50), B char(50), C char(50) );";
the debugger highlights the line : cmd.ExecuteNonQuery(); and throws the following exception:
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near '('.

Get rid of the parentheses you've added in the ADD clause. You don't have them in the single column version, and you don't need them with multiple columns either. Specify ADD once and then just comma-separate your list

If you're interacting with an SQL Server database (using T-SQL), you must not place parentheses around your list of column definitions even when adding multiple columns:
ALTER TABLE SqlCreatedTbl ADD A char(50), B char(50), C char(50);

Related

Sql Command error on C# Winforms

Im trying to copy a table structure in winforms app in C# and i always gets the error invalid syntax which is explained below :
This is my code
con.Open();
cmd.Connection =con;
cmd.CommandText="Create table temp as select * from Class";
cmd.ExecuteNonQuery();
con.Close();
and the error statement shows Incorrect syntax near 'Select' and
Incorrect syntax near class.
It should be,
cmd.CommandText="Create TABLE temp AS (select * from Class)";
You cannot execute this query because the "Select table" has Primary key or indexes.
try this:
CREATE TABLE temp
SELECT *
FROM class
CREATE INDEX index_column ON temp(index_column);
It is important to note, if the table has primary key you need to run another query "Alter table.." and set the primary key column of the table.
try this:
cmd.CommandText="Create TABLE temp select * from Class";

select from column if exist, if not value is NULL

I have a windows forms application (C#) that reads some data from MySQL database. In a new version I needed to add a new column in one of the tables (to add some functionality). Sometimes I need to make a restore database (from dump file). If I restore the old table from the old database (without the new column) I get "unnknown column" error.
How should I alter my SQL command to select data from this table? If 'newcolumn' exists, I need to select data, if not I need to select NULL.
MySqlDataAdapter da = new MySqlDataAdapter(
"SELECT my_id AS Id,myColumn1 AS Column1,myColumn2 AS Column2,
newcolumn AS NewColumn (here IF NOT EXIST = NULL)", connection);
da.Fill(izpis_podatkov);
Thank you!
If you restore the database but leave the code as it is then there's a mismatch between code and database schema. The simplest option would be to alter the table to add the missing column after you do the restore. Something like:
ALTER TABLE yourtable ADD newcolumn VARCHAR(255)
Obviously, changing the table, column name and data type to the appropriate values for your situation.
EDIT:
You could do something closer to what you actually asked by creating a stored procedure that would check for the existence of the column and add it if it is not there:
CREATE PROCEDURE `MyStoredProc` ()
BEGIN
IF NOT EXISTS (SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = `db_name` AND TABLE_NAME = `newtable` AND COLUMN_NAME = `newcolumn`)
BEGIN
ALTER TABLE 'newtable' ADD 'newcolumn' VARCHAR(255) NULL;
END
SELECT my_id AS Id, myColumn1 AS Column1, myColumn2 AS Column2, newcolumn AS NewColumn FROM newtable;
END
You would then need to change your C# code to call this stored procedure:
command = new MySqlCommand(procName, connection);
da = new MySqlDataAdapter(command);
command.ExecuteNonQuery();
da.Fill(izpis_podatkov);
I don't know MySql that well so please check the syntax of the stored procedure first!
You can't use a SQL Data Manipulation Language query, in MySQL, that mentions a nonexistent column in a table. The query planner in the MySQL server rejects it even if it shows up in a conditional context like IFNULL().
You could use a UNION ALL operation, like so
SELECT myColumn1, myColumn2, newColumn
FROM newTable
UNION ALL
SELECT myColumn1, myColumn2, NULL as newColumn
FROM oldTable
This will give you back the rows of the newTable and the rows of the oldTable as if they were a single table. It basically hides your two tables behind the UNION, pretending they have the same layout, making an alias for the missing column in oldTable.
Then, if you restore the oldTable from backup, you can truncate (remove all rows from) the newTable, if that makes sense in your application.
You can use the query I showed in a CREATE VIEW statement, then your production software will see it as if it were table.
CREATE VIEW table AS
SELECT myColumn1, myColumn2, newColumn
FROM newTable
UNION ALL
SELECT myColumn1, myColumn2, NULL as newColumn
FROM oldTable;

What is wrong with this sqllite alter table query?

I need to add column to table, for now I have this code:
public void InsertParameter(string ColumnName)
{
string sql = "ALTER TABLE table_name ADD :value1";
SQLiteCommand cmd = new SQLiteCommand(sql,conn);
cmd.Parameters.AddWithValue("value1", ColumnName);
cmd.ExecuteNonQuery();
}
But this give me syntax error:
near ":value1":syntax error
I really can't figure out what is wrong with this query?
The reason it doesn't work is that the syntax for SQLite's ALTER TABLE statement requires a column-name here instead of an arbitrary string-typed expr. This means you can't use a bind-parameter with it.
(Apparently, the implementation of prepared statements requires the table and column names to be known at “compile” time, so it can't be a variable.)
If you need a C# function that dynamically selects a column name at runtime, you need to dynamically create the SQL statement with a hard-coded column name. (Use double-quoting to prevent SQL injection attacks.)
string sql = "Alter Table table_name ADD "\"" + ColumnName.Replace("\"", "\"\"") + "\"";

SQL -Create table if not exists, and insert value

I check my SQL database to see if a column exists if not create, but I wanted to insert a string in that column, but only if the column didn´t exist.
Otherwise I handle that information in my C# code.
So far I have this code :
string query = "IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tabela' AND COLUMN_NAME = 'coluna') ALTER TABLE tabela ADD coluna varchar(50)" ;
SqlCommand command = new SqlCommand(query, con);
command.ExecuteNonQuery();
How should I do ?
Change your query to execute a block after the IF (psuedocode):
IF NOT EXISTS(...)
BEGIN
ALTER TABLE MyTable ...;
INSERT INTO MyTable ...;
END
Be sure to put semicolons at the end of the ALTER and INSERT commands, since you are sending these in a single command from an application, so SQL Server will see them as being all on one line.
You can write a trigger for each SELECT from the database object. In that you can first check if the column exists, and then you can do the needful. This you can achieve entirely by using SQL triggres (or even stored procedures
), C# has nothing to do with it :)
For more details on triggers, you can check this out

How to delete a record?

I have records in table1, if the records exist, it must copy into table2. I want to delete those records in a table1 once all the records are copied into another table2. Im still a beginner in database and with some researches, i found some tutorials on d internet how to connect with database, and the codes easy to understand so i came out with this program.This codes only do the copy part and i'm still lack of the delete part. Can help me figure out how to do the delete part? i found 2 reference in msdn, but i'm not sure and not understand on the codes given.
try
{
//create connection
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("Data Source=.dbname;Integrated Security=True;User Instance=True");
//command queries
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO tblSend (ip, msg, date) SELECT ip, msg, date FROM tblOutbox";
cmd.Connection = sqlConnection1;
sqlConnection1.Open(); //open con
cmd.ExecuteNonQuery(); //execute query
sqlConnection1.Close(); //close con
}
catch (System.Exception excep)
{
MessageBox.Show(excep.Message);
}
If i replace the query into this: //cmd.CommandText = "DELETE tblSend WHERE id = 5";
its only delete one rows. But what if many records involved? Do i need to consider the EOF things? DO i need to use DataGridView? Becoz the code i did didn't use DataGridView at all. i dont want the records to be displayed, i just want it to running behind.
No you do not need a worry about EOF or using a DataGridView. Just as you can use an ExecuteNonQuery method to insert multiple rows you can also do the same when using DELETE.
Data manipulation statements such as INSERT, UPDATE and DELETE do not generate a result set and hence you would normally use ExecuteNonQuery to run them. All the data manipulation runs in the database server engine.
If I understand correctly you need all data from table1 in table2 and then delete table1.
Options
1) It you need it once you could rename table1 to table2 and recreate table1
-- move the records to table 2, ok I assume it does not exist;)
RENAME TABLE table1 TO table2;
-- Create new table1 with same structure as table 2
CREATE TABLE table1 AS SELECT * FROM table2 WHERE 1=2;
2) Do a separate copy and delete assuming you have something like a primary key
-- copy the records
INSERT table2(field1, field2, ...) SELECT field1, field2, ... FROM table1;
-- and delete them
DELETE FROM table1;
3) Do it using C# but as this seems a database problem to me I would not go that far in pulling all the records to the client and then throwing them back.
DELETE FROM tblSend WHERE id = 5;
This will delete all rows that match the WHERE condition.
I am not sure I understand the relevance of the DataGridView. If it is databound, it will automatically remove the records as well. You only need to issue the delete query once and the rest should happen automatically, assuming you have the databinding correct.
What do you mean by "if they exist"? Compared to what?
To delete multiple records from table 1, you have to make a loop which goes through your table and compare.
Pseudo code:
forach (whatever as whut)
row = select whatever from table1.
if (whut == row)
copy row from table 1 to table 2;
Delete from table 1 where whut.id == row.id;
DELETE FROM tblSend WHERE id = 5;
This is the one solution for deletion a record.
If you want to set the identity key to 0 again, use this code
DBCC CHECKIDENT('tblSend', RESEED, 0);
Then press F5,

Categories