EF - pass null value to SQL column so default value gets inserted - sql-server

SQL Server table T2 has 2 columns:
Id INT NOT NULL
CreateDate DateTime NOT NULL, default = (getdate())
This statement inserts the CreateDate value correctly because it uses (getdate()) as default.
Insert T2 (Id)
Values (1)
So far so good. The problem is when I use Entity Framework to insert a row and still wish to use the default (getdate()) value.
Because the CreateDate is defined as NOT NULL, I cannot leave it blank or leave out of the Insert statement when using EF. But I want SQL to generate the timestamp on the server/database side.
Is there a way to handle this?

Thanks to squillman's reference to another SO post, I was able to find the answer.
Go to EDMX diagram, and you can set the StoreGeneratedPattern property to achieve what I am trying to do.
There are three Database Generated Options
Computed : The database generates a value when a row is inserted or updated.
Identity : The database generates a value when a row is inserted.
None : The database does not generate values.
EDIT: Although the picture shows Identity, I had to change it to Computed. The reason is that Identity option only works if the row is Inserted only. If the row is ever updated (other columns updated), then it caused an error. The Computed option seems to work fine with Insert (runs the default script) and Updates (to other columns, default script does not run again).

Related

Is NULL necessary?

Is NULL or NOT NULL necessary for Adding a column in SQL Server? (If you are going to run UPDATE statement after)
I tested without it locally, and it seems to work fine both in SQL and on the website; but I wanted to make sure before running release/production.
I looked up some other articles, including microsoft website. Some show it with, some without. SO articles say some benefits of NULL, like if you have information that may be added later. But assuming I am going to run UPDATE to add values after, will it matter?
I am guessing it does not matter from what I've tested and read.
ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150);
UPDATE [dbo].[MyTable] SET NewColumn ='Math' WHERE ID = 1
UPDATE [dbo].[MyTable] SET NewColumn ='Science' WHERE ID = 2
You can skip it, and by default the column will be created as NULL. However it is more legible if you indicate it explicitly.
Keep in mind that if your table already has data, you CANNOT add the column as NOT NULL. For this, you should firstly add the column as NULL, then UPDATE the values with non-null valid data and then alter column to NOT NULL.
Edit: Assuming the default behavior of the sql server when adding columns.
You don't have to write it, when you skip it column will be created as 'NULL'.
Following statements are equal:
ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150);
ALTER TABLE [dbo].[MyTable] ADD NewColumn varchar(150) NULL;
If you want to add a column and DB engine should guarantee you that this new column will be always populated you can add a NOT NULL column with a default value.
Other option will be to change the column to NOT NULL after the update.
I'd make sure you have something declarative. And if you are setting as "not null," be sure you have a default value or use can suffer LOTS of data loss if data previously exists. It makes me nervous because this an ALTER vs a CREATE.

Only allow current date/time on SQL Server insertion

I need a way to enforce a single value only within an inserted field, more precisely a DateTime field, that should always be set to the current date/time at insertion.
I am working on a university exercise and they want all the constraints to be done within the DB, ordinarily i would just put on a DEFAULT GetDate() and always use DEFAULT on inserts, but the exercise requirements prevent this.
Now for an integer i can do this(i've omitted the other fields, since they are irrelevant to the issue at hand) :
CREATE TABLE tester(
d INTEGER not null DEFAULT 3,
CONSTRAINT chkd CHECK(d = 3)
);
However what i want is the following :
CREATE TABLE tester(
d DATETIME not null DEFAULT GETDATE(),
CONSTRAINT chkd CHECK(d = ????????)
);
Re-iterating GetDate() in the check() will trigger an error on inserts, because the microseconds will cause a mismatch.
So i guess the first question is, is this possible? and if so(i hope so) how?
Don't track the date/time in the tester table. Instead, have a separate table with a column that references the ID of the tester table as a foreign key constraint. The new table will have one other column, a DateTime column. On insertion into the tester table, a trigger can be fired that will insert a row into the new table containing the ID of the newly-created tester row as well as the current date/time.
Based upon Ryan's comment got to this answer which is working
CREATE TRIGGER trigger_date ON [dbo].[tester]
FOR INSERT
AS
BEGIN
UPDATE tester SET d = GETDATE() WHERE id IN (SELECT id FROM INSERTED);
END
GO

Updating identity column in SQL Server and setting the seed starting value

I have a table filled with data and one of the columns - TrackingNumber - is an integer value. I have gotten a request to change it to auto-increment and to have it start the identity seed at 1000000. I know that I cannot alter a column to be an identity column in an existing table with data, so I have two options: either create an entirely new table and then move data from the old table into that new table or add an new identity column and update it with data from the old column.
The problem is that I need to retain all the existing values in column TrackingNumber. I have tried the following:
1) ALTER TABLE [dbo].[Table1]
ADD [TrackingNumber2] [bigint] IDENTITY (1000000, 1) NOT NULL
2) UPDATE [dbo].[Table1]
SET [TrackingNumber2]=[TrackingNumber]
3) ALTER TABLE [dbo].[Table1]
DROP COLUMN [TrackingNumber]
GO
4) EXEC sp_rename 'Table1.TrackingNumber2', 'TrackingNumber','COLUMN'
I got an error on step 2 - Updating new column with the value from the old column: "Cannot update identity column 'TrackingNumber2'"
Can anyone recommend a workaround?
You just need to set identity_insert on for this table so you can update the values. Make sure you turn it back off when you complete the update. :)
https://msdn.microsoft.com/en-us/library/ms188059.aspx
Are you sure you need to use an identity column? There are alternatives. For example, since SQL Server 2012 (and azure, too), there are these things called sequences. You can define a sequence to start at any number you like:
create sequence dbo.TrackingSequence
as int
start with 1000000
increment by 1
no maxvalue
no cycle
no cache
Then, you can alter the table such that the default value for the column in question defaults from the sequence:
alter table dbo.MyTable
add constraint [MyTable.TrackingNumber.Default.TrackingSequence]
default( next value for dbo.TrackingSequence ) for TrackingNumber
(If the column already has a default value, you need to remove that first - in a separate statement.)
A sequence works a lot like an identity, but you don't have to disrupt existing values or the column definition per se.
The only trick is to remember to not specify the value for TrackingNumber, and let the DB do its thing.
Sequences are cool in that you can have one sequence that is used by multiple tables, giving you somewhat shorter db-wide unique IDs than alternatives in the past. For such an application, you'd probably be better off with a bigint column - or know that the tables in question aren't going to be terribly long.
I ended up creating a new table and moving data in there

i started this replication wizard it adds GUID FIELD, how should i add data to this manually in future?

using replication in sql srv causes the addition of this guid field, it also adds a value to it
but when i insert new records to the db, i have to give somthing or the guid field
it should be like aaaaa-aaa-something and unique!!
this is a problem for me , how am i supposed to do this keeping it unique every time?
should sql srv automatically add some yhing?
The ROWGUIDCOL added by Merge Replication should be populated with... guids:
ROWGUIDCOL does not enforce uniqueness
of the values that are stored in the
column and does not automatically
generate values for new rows that are
inserted into the table. To generate
unique values for each column, either
use the NEWID function on INSERT
statements or specify the NEWID
function as the default for the
column.

SQL server trigger question

I am by no means a sql programmer and I am trying to accomplish something that I am pretty sure has been done a million times before.
I am trying to auto generate a customer number in sql every time a new customer is inserted, but the trigger (or sp?) will only work if at least the first name, last name and another value called case number is entered. If any of these fields are missing, the system generates an error. If the criteria is met, the system generates and assigns a unique id to that customer that begins with letters GL- and then uses 5 digit number so a customer John Doe would be GL-00001 and Jane Doe would be GL-00002.
I am sorry if I am asking too much but I am basically a select insert update guy and nothing more so thanks in advance for any help.
If I were in this situation, I would:
--Alter the table(s) so that first name, last name and case number are required (NOT NULL) columns. Handle your checks for required fields on the application side before submitting the record to the database.
--If it doesn't already exist, add an identity column to the customer table.
--Add a persisted computed column to the customer table that will format the identity column into the desired GL-00000 format.
/* Demo computed column for customer number */
create table #test (
id int identity,
customer_number as 'GL-' + left('00000', 5-len(cast(id as varchar(5)))) + cast(id as varchar(5)) persisted,
name char(20)
)
insert into #test (name) values ('Joe')
insert into #test (name) values ('BobbyS')
select * from #test
drop table #test
This should satisfy your requirements without the need to introduce the overhead of a trigger.
So what do you want to do? generate a customer number even when these fields arn't populated?
Have you looked at the SQL for the trigger? You can do this in SSMS (SQL Server Managment Studio) by going to the table in question in the Object Explorer, expanding the table and then expanding triggers.
If you open up the trigger you'll see what it does to generate the customer number. If you are unsure on how this code works, then post the code for the trigger up.
If you are making changes to an existing system i'd advise you to find out any implications that changing the way data is inputted works.
For example, others parts of the application may depend on all of the initial values being populated, so after changing the trigger to allow incomplete data to be added, you may inturn break something else.
You have probably a unique constraint and/or NOT NULL constraints set on the table.
Remove/Disable these (for example with the SQL-Server Management Console in Design Mode) and then try again to insert the data. Keep in mind, that you will probably not be able to enable the constraints after your insert, since you are violating conditions after the insert. Only disable or reomve the constraints, if you are absolutely sure that they are unecessary.
Here's example syntax (you need to know the constraint names):
--disable
ALTER TABLE customer NOCHECK CONSTRAINT your_constraint_name
--enable
ALTER TABLE customer CHECK CONSTRAINT your_constraint_name
Caution: If I were you, I'd rather try to insert dummy values for the not null columns like this:
insert into customers select afield , 1 as dummyvalue, 2 as dummyvalue from your datasource
A very easy way to do this would be to create a table of this sort of structure:
CustomerID of type in that is a primary key and set it as identity
CustomerIDPrfix of type varchar(3) which stores GL- as a default value.
Then add your other fields and set them to NOT NULL.
If that way is not acceptable and you do need to write a trigger check out these two articles:
http://msdn.microsoft.com/en-us/library/aa258254(SQL.80).aspx
http://www.kodyaz.com/articles/sql-trigger-example-in-sql-server-2008.aspx
Basiclly it is all about getting the logic right to check if the fields are blank. Experiment with a test database on your local machine. This will help you get it right.

Resources