SQL Server 2005 CE 3.5 Re seed IDENTITY - sql-server-2005

I have inserted some rows into a data table with
Set Identity_insert tblEvent on
I then attempt to 'reseed' the Identity field
int MaxId = this.MaxID()+1;
string upgrade = "ALTER TABLE " + Table + " ALTER COLUMN ID IDENTITY("+ MaxId.ToString() +",1)";
System.Data.SqlServerCe.SqlCeCommand cmd = new System.Data.SqlServerCe.SqlCeCommand(upgrade, connection);
cmd.CommandType = System.Data.CommandType.Text;
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
'MaxId' is determined by
int MaxId = 0;
string upgrade = "select Max(ID) from " + Table;
System.Data.SqlServerCe.SqlCeCommand cmd = new System.Data.SqlServerCe.SqlCeCommand(upgrade, connection);
cmd.CommandType = System.Data.CommandType.Text;
connection.Open();
MaxId = (int)cmd.ExecuteScalar();
connection.Close();
return MaxId;
However, if I query Max(ID) again after seeding it has'nt changed
Any idea's aprreciated

Try this:
string upgrade = " DBCC CHECKIDENT('[" + Table + "]', RESEED, " + (MaxId + 1)+ " )"

weird, could it be a permissions issue. you should have seen an exception though, unless the exception is gobbled up by a catch all.

Related

update table statement - Violation of Primary Key constraint

I tried this c# update if record exists else insert new record to update my table, if records exists.
But I run into the exception: "Violation of Primary Key constraint". Because of this line cmdCount.Parameters.AddWithValue("#local_programs_id", local_programs_id); and because there's already a value for local_programs_id in the table
What have I done wrong?
Thanks a lot.
SqlConnection connection = new SqlConnection(sqlConnection_String);
SqlCommand cmdCount = new SqlCommand("SELECT count(*) FROM " + datenbankname + " WHERE local_programs_id = #local_programs_id" , connection);
cmdCount.Parameters.AddWithValue("#local_programs_id", local_programs_id);
connection.Open();
int count = (int)cmdCount.ExecuteScalar();
Console.WriteLine("count1 " + count);
if (count > 0)
{
SqlCommand updateCommand = new SqlCommand("UPDATE " + datenbankname +
" SET local_programs_Id = #local_programs_Id, " +
"program_name = #program_name, " +
"publisher_name = #publisher_name, " +
"program_version = #program_version, " +
"install_dir = #install_dir, " +
"uninstall_dir = #uninstall_dir, " +
"inserted_at = #inserted_at, " +
"direct_link_available = #direct_link_available", connection);
updateCommand.Parameters.AddWithValue("#local_programs_Id", local_programs_id);
updateCommand.Parameters.AddWithValue("#program_name", program_names);
updateCommand.Parameters.AddWithValue("#publisher_name", publisher_names);
updateCommand.Parameters.AddWithValue("#program_version", program_version);
updateCommand.Parameters.AddWithValue("#install_dir", install_location);
updateCommand.Parameters.AddWithValue("#uninstall_dir", uninstall_location);
updateCommand.Parameters.AddWithValue("#inserted_at", DateTime.Now);
updateCommand.Parameters.AddWithValue("#direct_link_available", direct_link_available);
int rowsUpdated = updateCommand.ExecuteNonQuery();
Console.WriteLine("rowsUpdated " + rowsUpdated);
}
else
{
Console.WriteLine("inserted1 ");
string query = "INSERT INTO " + datenbankname + " (local_programs_Id, program_name, publisher_name, program_version, install_dir, uninstall_dir, inserted_at)";
query += " VALUES (#local_programs_Id, #program_name, #publisher_name, #program_version, #install_dir, #uninstall_dir, #inserted_at)";
SqlCommand insertCommand = new SqlCommand(query, connection);
insertCommand.Parameters.AddWithValue("#local_programs_Id", local_programs_id);
insertCommand.Parameters.AddWithValue("#program_name", program_names);
insertCommand.Parameters.AddWithValue("#publisher_name", publisher_names);
insertCommand.Parameters.AddWithValue("#program_version", program_version);
insertCommand.Parameters.AddWithValue("#install_dir", install_location);
insertCommand.Parameters.AddWithValue("#uninstall_dir", uninstall_location);
insertCommand.Parameters.AddWithValue("#inserted_at", DateTime.Now);
int rowsInserted = insertCommand.ExecuteNonQuery();
}
You don't have a where filter on your update statement and you are updating the primary key column. You're essentially doing
Check if there is a row with X primary key value
If there is then update every row to have that primary key value.
If not then insert.
You should not be updating the primary key ever, even in your case where it isn't supposed to be changing. There are lots of annoying behaviour that could come from this, one that springs to mind is where this primary key is referenced in a foreign key in another table - this update statement would put locks on the other table (potentially a full table lock if it's not indexed).
You also should not be using a count(*) to determine whether the row exists. This will only tell you if the row exists at that point in time and is visible to your session (you can't see non-committed transactions). Most RDBMSs have a MERGE operation you can use for this behaviour, have a look at your RDBMSs docs for it. Alternatively, it might be okay to optimistically try the insert statement and if it throws a duplicate row error then you do the update statement.

MS SQL Invalid column name error

This code returns the following error:
"System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'a51'"
a51 is the correct value inside of the record I'm looking for in the EstablishmentCode column of the Establishments table. Account ID is used to find all entries on the Establishments table with that account ID and populate a dataset with Establishment Code values. Account ID value comes from a session variable. Then I use each of these values in a loop where each iteration calls a datareader while loop. Hope I explained this clearly, but I would gladly clarify more if needed. Here's my code.
myConnection.Open();
SqlCommand getEst = new SqlCommand("SELECT EstablishmentCode FROM Establishments WHERE AccountID = " + ID, myConnection);
da = new SqlDataAdapter(getEst);
ds = new DataSet();
da.Fill(ds);
int maxrows = ds.Tables[0].Rows.Count;
for (int x = 0; x < maxrows; x++)
{
getPhones = new SqlCommand("SELECT * FROM DispatcherPhones WHERE EstablishmentCode = " + ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString(), myConnection);
myReader = getPhones.ExecuteReader();
while (myReader.Read())
{
Response.Write("<section id='phone" + myReader["Phone"].ToString() + "' style='padding:20px'>");
Response.Write("<section>Phone Number<br><div class='phone'>" + myReader["Phone"].ToString() + "</div></section>");
Response.Write("<section>Location Code<br><div class='name'>" + myReader["EstablishmentCode"].ToString() + "</div></section>");
Response.Write("<section>Active<br><div class='name'>" + myReader["Active"].ToString() + "</div></section>");
Response.Write("<section class='flex phoneButtonSection'>");
Response.Write("<button type=\"button\" onclick=\"showPhoneForm('" + myReader["ID"].ToString() + "');\">CHANGE</button>");
Response.Write("<button type=\"button\" onclick=\"deletePhones('" + myReader["ID"].ToString() + "');\">DELETE</button>");
Response.Write("</section>");
Response.Write("</section>");
}
myReader.Close();
}
myReader.Close();
myConnection.Close();
String literals in SQL are denoted by single quotes ('s) which are missing for your value:
getPhones = new SqlCommand
("SELECT * " +
"FROM DispatcherPhones
"WHERE EstablishmentCode = '" +
// Here -------------------^
ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString() +
"'" // And here
, myConnection);
Mandatory comment: concatinating strings in order to create SQL statements may leave your code exposed to SQL injection attacks. You should consider using prepared statements instead.

SQL Dynamic Query - Incorrect syntax near '#WhereClause'

//_whereclause is: where (lastName like '%Davis%')
public static MyList GetAll(string _whereclause)
{
using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
string selectSQL = "";
selectSQL += "SELECT #RecordCount = COUNT(*) FROM [PersonnelTable]";
if (_whereclause != string.Empty)
{
selectSQL += " #WhereClause";
}
using (SqlCommand myCommand = new SqlCommand(selectSQL, myConnection))
{
myCommand.CommandType = CommandType.Text;
SqlParameter whereClauseParam = new SqlParameter("#WhereClause", SqlDbType.NVarChar, 4000);
whereClauseParam.Value = _whereclause;
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{..............
If I run it with the #WhereClause I get error:
Incorrect syntax near '#WhereClause'.
Your select query should be like
selectSQL += "SELECT #RecordCount = COUNT(*) FROM [PersonnelTable] where (lastName like '%" + #WhereClause + "%')";
Assuming that:
SqlParameter whereClauseParam = new SqlParameter("#WhereClause", SqlDbType.NVarChar, 4000);
whereClauseParam.Value = _whereclause; //Here you are getting the value as 'Davis'
But in case you are getting the value in it as where (lastName like '%Davis%') then you simply need to add a space after
selectSQL += "SELECT #RecordCount = COUNT(*) FROM [PersonnelTable] ";
^^ here

Mistakenly inserted date in month field sql how to change

Unfortunately I inserted a date as dd-mm-yyyy in sql but it assumed it as mm-dd-yyyy Now more than 50 fields are like this how can I change this? I found an exception as invalid date when I was taking report by date that more than 12. Now I want to change all of the inserted fields without losting it
UPDATE tableName
SET dateColumn = MONTH(dateColumn) + "-" + DAY(vdateColumn) + "-" + YEAR(dateColumn)
I hope this work even though I didn't test it myself. Please use a WHERE clause to limit the update only to the impacted rows.
UPDATE yourTable
SET yourDateColumn = Convert(datetime,yourDateColumn,101)
Let me know if this fixes your issue.
Nothing worked but finally I reset it manually by c# console
Console.WriteLine("Changing Orderdate");
Console.WriteLine("~~~~~~~~~~~~~~~~~~");
List<string> date = new List<string>();
List<string> no = new List<string>();
int i = 0;
SqlCommand cmd = new SqlCommand("select DATEPART(yyyy,orderdate) as y, DATEPART(mm,orderdate) as m, DATEPART(dd,orderdate) as d, bno from bill", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
date.Add(dr["y"].ToString() + "-" + dr["d"].ToString() + "-" + dr["m"].ToString());
no.Add(dr["bno"].ToString());
}
con.Close();
foreach (var a in date)
{
Console.WriteLine("Inserting: " + date[i] + " With " + no[i]);
SqlCommand cmd2 = new SqlCommand("update bill set orderdate = '" + date[i] + "' where bno = " + no[i], con);
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
i++;
}
Console.WriteLine("Order date changing completed \n\n");
Thank you for sharing your precious time thanks friends

Sql query added to title?

In c# Windows Forms:
I'm having trouble adding a sql query result as text to a ToolStripMenuItem.Text.
The ToolStripMenuItem title should be, the company + how many orders there are in the sql table for this company which should update every x secounds.
Every 5 seconds it adds the query result to the text. My problem is that is "adds" it.
After the first 5 seconds it looks OK "rexton 1" but 5 seconds after it shows "rexton 1 1" and so on...
Here is my code:
//Rexton ordre klar til bestilling
SqlConnection con = new SqlConnection(#"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();
command.CommandText = "SELECT COUNT(*) from bestillinger WHERE firma = #rexton and udlevering BETWEEN #date and #dateadd";
command.Parameters.AddWithValue("#bernafon", "Bernafon");
command.Parameters.AddWithValue("#gn_resound", "GN Resound");
command.Parameters.AddWithValue("#oticon", "Oticon");
command.Parameters.AddWithValue("#phonak", "Phonak");
command.Parameters.AddWithValue("#rexton", "Rexton");
command.Parameters.AddWithValue("#siemens", "Siemens");
command.Parameters.AddWithValue("#widex", "Widex");
con.Open();
command.ExecuteNonQuery();
string result = command.ExecuteScalar().ToString();
con.Close();
if (result != "0")
{
rextonToolStripMenuItem.Text = rextonToolStripMenuItem.Text + " " + result;
rextonToolStripMenuItem.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF1919");
}
it is because you are setting rextonToolStripMenuItem.Text to rextonToolStripMenuItem.Text + " " + result which is appending to previous text
either set text to blank and set it again or just say
rextonToolStripMenuItem.Text = "rexton " + result