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";
Related
I have the following SQL query which I am sending from a C# program:
DECLARE #id as int
SELECT #id = max(fault_catagory_ident) FROM fault_catagory_list
INSERT INTO fault_catagory_list (fault_catagory_ident, fault_catagory)
VALUES (#id + 1, 'TEST')
SELECT #id + 1
The 'fault_catagory' value is coming from my program, but the ident value needs to be the next number in line (primary key) from the existing table in the database. My C# code is parameterising values for security.
I have two problems:
How can I get the #id + 1 value returned to my program (executeNonQuery doesn't return anything)?
How can I get #id as a parametarised value for the insert command?
I am wondering if my primary key could be automated in some way?
I want to carry all this out in one single query, as there will be a risk of multiple logins running this same query. If any happened to run simultainiously, the #id value may get duplicated and one would fail.
Apologies if there isn't enough info here, I'm on a learning curve!
Any advice would be greatly appreciated. Thanks in advance.
I think that you will find everything you need in this example provided in MSDN:
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executescalar?view=dotnet-plat-ext-5.0
in short:
to return a single parameter from a query ull use ExecuteScalar()
parameters are added to a query through the SqlCommand class provided in System.Data.SqlClient.
cheers!
Thanks for the advice, think I have found the solution...
Firstly I need to recreate the table with the primary key column using the IDENTITY constraint (makes sense to use this now I know it exists!). Found a guide here (though it will mean some rebuilding of primary/foreign key links) https://www.datameer.com/blog/how-to-add-an-identity-to-an-existing-column-in-sql/
Then in C# program, use SqlCommand.executeScalar to return the identity value
Int identReturn = 0;
identReturn = (Int32)cmd.ExecuteScalar();
Thanks again for the responses.
While I don't agree with the logic in which you are choosing identity row values for the inserted rows, you could certainly acheive that using IDENTITY() column attribute in the SQL table definition.
In case you have multiple SELECTs in your SQL command,
everytime you have a SELECT in your sql command, a new table is added to the passed in dataset to the data adapter.
string sql = "
DECLARE #id as int
SELECT #id = max(fault_catagory_ident) FROM fault_catagory_list
INSERT INTO fault_catagory_list (fault_catagory_ident, fault_catagory)
VALUES (#id + 1, 'TEST')
SELECT #id + 1";
SqlCommand cmd = new SqlCommand(sql, conn); // assuming you already set connection
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
Console.WriteLine( ds.Tables[0].Rows[0][0]); // this will print #id
Console.WriteLine( ds.Tables[1].Rows[0][0]); // this will print #id + 1
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("\"", "\"\"") + "\"";
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
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);
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,