Update older records when a new column is added - c#

In my system, the client will fill in their information to register an account. For new registrations, the record will contain a new check-box option.
My Question is, how do I update the old records so that they contain a checked value for the check-box option that has been added?
My supervisor suggest I patch the data but I'm not sure where to start with this.

I think I got your question. You need to add few Boolean fields to your existing table with DEFAULT value TRUE.
ALTER TABLE TABLE1 add checkField bit default 1
You need to map the corresponding field to a check box in your UI. For existing client it will checked as the field is set true in database.

I assume you want to add a new bit column to an existing table and want all existing records have the value 1 in it.
To do this you first create the new column and than right after set all existing records to 1
alter table MyTable
add CheckedField bit
update MyTable set CheckedField = 1
If the new column is mandatory than you can do it like this :
alter table MyTable
add CheckedField bit not null default (1)

Related

Insert to Oracle Database always creates new Index ID and doesn't take the old one

I am currently trying to insert a DataRow into an Oracle SQL Database. The entry gets inserted into the Database but always gets a new ID. I am providing an ID in the Insert Command but it always uses an auto increment and doesn't let me insert my ID.
What can I do?
There are 2 possible solutions to your problem.
Set column as NOT to be "Identity" column. This will take care of
your issue without any hassle.
If you must keep that column as "Identity" column, set "Generated"
property to "By Default on Null". This will ensure that when you are
NOT passing any value for ID, the system generates next sequence
number automatically.
For solution 2:
DDL Statement: ID NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY INCREMENT BY 1
Table Creation in SQL Developer:

How to detect which column's value has updated in a Table

Suppose I have a student registration form with 85 fields in my c# project and there are three buttons Save, Update, Delete.
The person who update the field knows very well that which field has updated but how other person will know that which field has updated ? Because...
If I click update button without changing any value, the Update query execute and the same update query execute too when I click update button with some changes.
So I want that database should detect which field has updated in update query.
The traditional way says that store the previous values and then compare them with new values one by one field. But this slow down the performance.
Any smart way ?
You can implement optimistic concurrent using a rowversion column. This avoids the need to check the old/new values of each column individually. Specify the original rowversion in the WHERE clause of the UPDATE statement and verify a row was updated. Proc example:
CREATE TABLE dbo.OptimisticConcurrencyExample(
OptimisticConcurrencyExampleID int NOT NULL
CONSTRAINT PK_OptimisticConcurrencyExample PRIMARY KEY
, Column1 int NOT NULL
, Column2 int NOT NULL
, Column3 int NOT NULL
, RowVersion rowversion
);
GO
CREATE PROC dbo.UpdateOptimisticConcurrencyExample
#OptimisticConcurrencyExampleID int
, #Column1 int
, #Column2 int
, #Column3 int
, #OriginalRowVersion rowversion
AS
UPDATE dbo.OptimisticConcurrencyExample
SET
Column1 = #Column1
, Column2 = #Column2
, Column3 = #Column3
WHERE
OptimisticConcurrencyExampleID = #OptimisticConcurrencyExampleID
AND RowVersion = #OriginalRowVersion;
IF ##ROWCOUNT = 0
BEGIN
RAISERROR('data updated or deleted by another user', 16, 1);
END
GO
When an optimistic concurrency error occurs, the app code can refresh the data with the current values, let the user know someone else updated the row, and allow the user to re-enter changes. You could get fancy and transparently merge pending changes in code (checking old/new values for each column) and notifying the user only if a conflict occurs. Similarly, you could present the user with a merge form after a conflict with the entered and current values side-by-side and the different values marked, etc.
But given conflicts are typically rare (unlikely that different users will update the same student record at the same time), the additional development effort may not be worth the trouble.
I have one way to do that thing using table versioning using that you can maintain every update, create, delete the record.
Tutorial for table versioning
Another Tutorial
The second way is you have to add audit table or field that store SQL query and also store which user change the data and also store last modified date like that.
Why do you need a save button and an update button? Same thing, right?
Modify the logic in your program to allow an update only if the user
changes the data on the student registration form relative to the
data in the database.
Read record from database
Store record data in a local DataRow or List
Load data onto the student registration form
update_button.enable = false
delete_button.enable = true
Create TextChange event methods for each TextBox on the student registration form
When a TextChange event method fires, compare the TextBox text to the corresponding DataRow field or List item (case
insensitive).
If they don't match, enable the update button
If the user clicks the update button, update the record and disable the update button

How do I retroactively change a default value for a column in SQL Server?

When I add a default constraint to a Column in SQL Server 2017 it sets the default for all future record entries.
ALTER TABLE Products ADD CONSTRAINT DFC_PictureDefault DEFAULT [some_value] FOR PICTURE
When I did this the first time the column entries were null and it was easy for me to just write an UPDATE statement. But this is for a web application and I want to write a statement that will be able to DROP the current CONSTRAINT and ADD a new one. The UPDATE all of the records with the old DEFAULT value. I can figure out how to retrieve the old DEFAULT value for the WHERE clause of my UPDATE statement.
A practical use for this is if a client has an image of a company logo for all products that don't currently have a product image but decides to alter their brand and change their logo.

Visual studio SQL default value not showing on windows form when adding new record

I have created a SQL table in Visual studio and set a default value on a field.
The table is connected to my C# project (in the same solution) and pulls through fine, however the default values are not appearing when a new row is created via a windows form.
Info from comment questions:
It doesn't appear on the form when I click the + for a new row.
When a row is added from the database the defaults are there.
Added a new row via the form, left the fields with default values blank, saved, re opened and no default values.
Based on this W3Schools Tutorials
The default value will be added to all new records IF no other value is specified.
So the Default value will not show until you save the row to the database, you can add it programatically, but the Default value constraint is used to assign a value if there is no values provided in this column
You can save these default values in the application Settings and use it when new row is added
textBox1.Text = Properties.Settings.Default.TextBoxDefaultValue;
If you are facing an issue when defining default value in Visual Studio try adding a Default Constraint using SQL query:
ALTER TABLE XXX
ADD CONSTRAINT def_Retired
DEFAULT 'N' FOR Retired;
UPDATE 1
On the form designer, click on the BindingNavigator, In the Properties window set the AddNewItem property to (none)
Try adding the following code to the bindingNavigatorAddNewItem_Click event
private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e) {
vehiclesBindingSource.AddNew();
Textbox1.Text = Properties.Settings.Default.Text1default;
};
It doesn't appear on the form when I click the + for a new row.
The DataGridView does not know anything about default values in the database table. Accordingly, you must specify the default values in the DataGridView.
Or if you are using data binding, you can specify default values in the DataTable.
When a row is added from the database the defaults are there.
It's right, because in the database they are set.
Added a new row via the form, left the fields with default values blank, saved, re opened and no default values.
If you insert data into the database in the following way:
insert into SomeTable ('Retired') values ('');
then no default value will be used. With high probability I can assume that at the moment you passes empty values from DataGridView, if they are not set. This is wrong!
If you insert data into the database in the following way:
insert into SomeTable ('Last Mileage') values (0);
then the default value for Retired column will be used. It should be so.
Therefore, you must correctly design the Insert statement, completely omitting those columns for which should be used the default value in the database itself.
Summing up. You either have to fill the default values in the DataGridView/DataTable or dynamically construct the Insert statement, completely omitting the not specified values.
You are assigning default values in forms that are dynamically generated. You may need to evaluate whether the components of your client side/server side scripting were also made to accommodate this dynamic behavior in parallel.
Default Constraint Works only if you are not specifying the Column in the Insert List.
Suppose I have a Table Like This
CREATE TABLE MyInfo
(
Id INT IDENTITY(1,1),
Nm VARCHAR(50),
MyDate DATE DEFAULT(GETDATE())
)
I'm specifying the Values Like this
INSERT INTO MyInfo
(
Nm,
MyDate
)
SELECT
Nm = 'A',
MyDate = '02/23/93'
UNION
SELECT
Nm = 'B',
MyDate = NULL
And The Result will be Like this
Now I insert a row without specifying MyDate Column
INSERT INTO MyInfo
(
Nm
)
VALUES('C')
And the MyDate was populated bu Default values
Default Constraint is meant to assign the value if the column is not specified in the insert list. If what you need is to set a Default value if The Inserted value IS NULL or empty, Try using triggers

Alter column identity with Microsoft.SqlServer.Smo

I've trying to change a column IDENTITY using Microsoft.SqlServer.Smo from a table with no dependencies and with all the data loaded previously (from another DB) but i get an error like this "Modifying the Identity property of the Column object is not allowed. You must drop and recreate the object with the desired property". The thing is that i tried to do this with Management Studio and it has no problem with it. Do you have any suggestions?. Thanks in Advance
This is the code:
foreach (Column source in sourcetable.Columns)
{
try
{
if(source.Identity)
{
Column column = copiedtable.Columns[source.Name];
// column.Computed = source.Computed;
// column.ComputedText = source.ComputedText;
column.Identity = source.Identity;
column.IdentityIncrement = source.IdentityIncrement;
column.IdentitySeed = source.IdentitySeed;
column.Alter();
}
}
catch { }
}
Try doing it in SSMS again and choose to script the action out instead of applying it directly. You'll find that it creates a temporary table with the identity property set to true (and everything else the same), copies your data from the live table into the temp table, drops the live table, and renames the temp table to be the live table. You'll need to do something similar with SMO.
Copying the table is easy enough: iterate over the columns, indexes, foreign keys, etc and create your new table that way (taking care to set the identity property correctly properly before you call Create()). For moving the data, take a look at the Transfer class. Once that's done, it's a drop and rename (or a rename and rename if you want to be safe).
I'm a little surprised that SMO doesn't do this somehow under the covers (since SSMS uses SMO under the covers). If I find something else that makes it do this automatically, I'll let you know.
Are you trying to update an existing record, or add a new record? If you're adding a new record, then do an insert. If you're updating an existing record, don't overwrite the identity column value.
To insert identity values into a table in SQL Server you must tell the database to allow you to do this. Syntax is:
Set Identity_Insert [table] ON
When you're done you need to turn it off again.
Set Identity_Insert [table] OFF

Categories

Resources