I have a table with 30+ fields. Many of the fields allows NULL. My question is if I want to update the field(s) that changed value, how do I do that with stored procedure? Currently I am selecting a specific row and storing all the current values in the table. Next I would have to compare each variable to the new one to see if they are different, and if it is, then add that field name and the new variable to the string query. Then execute. Is there a more efficient way of doing this? As you imagine, it is a pain to compare all 30+ fields, especially since many are Nullable. Thank you.
So here is my logic so far in my stored procedure:
Have all the parameters that are nullable and set them to null (since it is optional).
DECLARE a variable for each field which I will be testing (30+ fields)
SELECT the row identify by the ID passed in from the parameter (primary key).
Store all the values into each variable.
Check each value to see if it IS NULL. If so, that means the user did not provide the field so no update in necessary for that field. If the parameter value IS NOT NULL, check if it is == to the value SELECTED from the database. If the value !=, then add it to the query string to be updated.
Execute the update query string.
Related
I created mvc 4 application that can upload data into database using sql bulk copy upload method.
Once I select excel file, it can upload data into the system.
this is working fine, now I want to add default value if excel field is null
this is how it extract column values of excels
"s1.Gender, " +
"s1.Country_of_Birth, " +
"s1.Date_of_Birth, " +
I want to add default value from code level , I already handle this using database level.
for example to add default value for "date of birth" I added following constraint
ALTER TABLE [dbo].[tbl_HEI_student] ADD CONSTRAINT [DF_tbl_HEI_student_Date_of_Birth] DEFAULT (getdate()) FOR [Date_of_Birth]
But when I upload excel file into db ,SQL bulk copy upload method is ignoring adding that default value database .
How can I add default value from controller method
Your problem must be that the column allows NULLS.
In case your column allows NULL and you provide a NULL value on the insert the NULL WILL be inserted. If no value is provided for the column the DEFAULT will be considered.
Setup your column to NOT NULL.
ALTER TABLE [dbo].[tbl_HEI_student] ALTER COLUMN [Date_of_Birth] DATE NOT NULL
Here is the Default Definition.
EDIT:
As you have noticed, you can't BulkInsert the NULLS to that columns and make the DEFAULT value prevail on SqlServer side, and the NOT NULL i suggested will enforce that either no value is supplied or something other than NULL.
I can see a few options.
Either deal with them .NET side by setting the value to your default (you will have to show you .NET code if you want help with that)
doing one bulk for rows with value and another for rows without and removing the mapping for that column, the default constraint will take action
Setting the row back to allow NULLS, do the bulk as you were doing, and doing an update after the bulk to set the NULLS to your default value.
I know BULK INSERT and BCP both have a qualifier as shown here to deal with the NULL values. The same option is available in the .NET SqlBulkCopy options.
Here is another question related to your problem.
Keep in mind your database schema should help you enforce your business rules and keep your data clean. If the date should never be NULL, keep the column as NOT NULL and do your solution accordingly.
I'm having an issue with adding new patients to my SQL database. When I do so, the following error appears, and an SQL Exception is thrown.
Cannot insert the value NULL into column 'ID', table 'IntelliMedDB.dbo.PatientRecord'; column does not allow nulls. INSERT fails.
The information contained in all of the values that are added as parameters aren't actually null. They all have information inside them.
Now, to protect against SQL Injection attacks, all of my queries use parameterized values.
I had an MS Access DB that handled all of this fine (same queries, I've just switched from using OleDBCommand to SqlCommand. Other than that, nothing's changed).
Here's the "INSERT INTO" statement, followed by a parameterized query, just so you all can see what I've done:
INSERT INTO PatientRecord (patientID, firstName, lastName, patientGender, dateOfBirth, residentialAddress, postalAddress, nationalHealthNumber, telephoneNumber, cellphoneNumber)
VALUES (#patientIDNumber, #recepPatFirstName, #recepPatLastName, #recepPatGender, #recepPatDateOfBirth, #recepPatResidentialAddress, #recepPatPostalAddress, #recepNHINumber, #recepPatTelephone, #recepPatCellularNumber)";
(I apologize for the length of the query).
And now, one of the parameterized values:
recepPatRecordCommand.Parameters.AddWithValue("#recepPatFirstName", patRecepFirstName);
Any help gratefully received.
Thank you!
You should edit your question with the definition of the table and the database you are using.
However, the problem is pretty clear. The PatientRecord table has a column called id which is declared to be NOT NULL. That means that NULL values are not allowed -- and you get the error that you see. By not setting a value explicitly in the insert, the value is set to a default. With no default, the value is set to NULL.
Normally, such columns have a default value or are declared to be identity (or auto incrementing).
I think you should probably fix the table so the NOT NULL columns have default values. Or, put in an appropriate value for the id column. For this, you would add id to the column list and then a corresponding value in the values list.
Although your INSERT statement refers to patientId, the error message you are seeing refers to ID.
You are seeing this error because no value for ID is specified.
Open your table in Design
Select your column and go to Column Properties
Under Indentity Specification, set (Is Identity)=Yes and Indentity Increment=1
In my program if i doesn't select a drop down list they are storing as 0 or null values in table but they are not visible in view.Can any of u suggest me other option rather than 0 or null in database.
you can enter some default values in your specific column that can be done in several ways
on insert statement if dropdown value is not selected you can pass some default values like dash (-)
for specific table where you need default value you can set default value using query
ex:
ALTER TABLE UserDetails ADD CONSTRAINT DF_SomeName DEFAULT N'-' FOR Email_ID;
hope this will help
I have a table userdata which has these columns:
userId
userName
userEmail
userContact
userDob
userAdd
userImage
userPass
I am using a stored procedure to select data from this table.
Now I want to update this table with a stored procedure. I am able to update this table with stored procedure but my requirement is in profile.aspx I allow user to update all columns with stored procedure. But in other forms I want user to update a few columns only, for example on setting.aspx page I allow user to update only userPass column.
So I have to make another stored procedure. And I have many tables like this. And I wondered how many stored procedure I have to create to update many tables with different columns.
Can anyone suggest a short way so that I can do this with only one stored procedure per table to update whole table or individual columns, too or any c# code to shorten this?
Thanks in advance
You can use the ISNULL function in MS SQL Server, which is explained by below statement from MSDN.
Replaces NULL with the specified replacement value.
You can write one stored procedure, which updates all the fields that you want to update in various operations. Call the same procedure from all pages. Then from a page only pass relevant parameters for that page & for the remaining parameters (that are not relevant to that page) pass null.
Your stored procedure should be like this
UPDATE dbo.userTable SET
userName = ISNull(#userName, userName),
userEmail= ISNull(#userEmail, userEmail),
-- list of all your table fields goes here
WHERE userID = #userID
What this will do is, if you pass the parameter; it will update value for that field; and if you pass null for any field it will update that field with its existing value. So that field will not be affected in the update operation.
You can have single stored proc with multiple if.. else.. condition to control updation of each single field. Then you can pass them as parameter to control which field to update.
I think you can do like this:
At the front page, you should set the fields not editable that you didn't want to update, but pass the values as parameters to the store-procedure. In store-procedure, you campare the old value of these fields to the correspondding parameters, If not equal, update it, otherwise, do nothing with these fields.
you could use something like this:
UPDATE tbl t
SET t.userName = CASE WHEN #userName IS NULL THEN t.userName ELSE #userName END
, t.userEmail = CASE WHEN #userEmail IS NULL THEN t.userEmail ELSE #userEmail END
, ...
WHERE t.userName = CASE WHEN #WHERE_userName IS NULL THEN t.userName ELSE #WHERE_userName END
AND ...
So if you do not want to update specific field just pass DBNull.Value from the code to the procedure call for that parameter.
Keep in mind that this will work only if you do not intend to update a field with NULL value.
If you need nulls you could then rewrite a little bit the code to make it work with nulls. If you need further help, just put a comment.
Get your all data in Datatable for which you need to update.
use datatable.WriteXML method and get in Stream object all the string use XmlWriteMode.IgnoreSchema to get only data.
DataTable dt = new DataTable();
dt.WriteXml(stream object ,XmlWriteMode.IgnoreSchema)
Now create procedure which accept Varchar(max) parameter and pass Stream object to the procedure.
After that you are able to use Openxml or get all this thing in XML variable in Sqlserver
get all data in #tablevariable or in #temp table.
Openxml in sqlserver
or
For Xml for XMl variable
then you will get every thing in one table use that table to update your
database table base on your primary key ID
like....
SQl qquery is like below
Update "Database Table Name"
set .........
from "GetDatafromc#table"
Unfortunately I found out that LINQ ignores the default values when inserting rows. The work around is to change the Auto Generated Value property of each column in the DBML to True
This is fine and dandy for tables that only have a few of these columns, but i have a table that has 20+ that need to default.
Before I spend the time creating a stored procedure, will a stored procedure even respect/use the default values?
EDIT: LINQ ignores the default values when inserting rows
This means if I have 10 columns, and I only give values for the first 3 columns with my LINQ insert, the remaining 7 columns will have a value of null instead of the default values defined by the table
Any SQL insert will respect the default values as long you don't explicitly pass in NULLS for the column values.
This will work fine in a stored procedure.