Is it possible to assign to a UNIQUEIDENTIFIER field automatically in each insertion? - sql

I have a table in which I have an INT IDENTITY(1,1) PRIMARY KEY field, and right next to it an UNIQUEIDENTIFIER field which I would like to be automatically assigned upon each insertion on the table. I tried setting DEFAULT NEWID(), but it only works if I do INSERT INTO TableName VALUES (DEFAULT, a, b, c, d, ...). What I would like would be to be able to do INSERT INTO TableName VALUES (a, b, c, d, ...) and the UNIQUEIDENTIFIER field be automatically assigned just like the primary key field. Is that possible? Please not that, although it is a valid thing to do, I don't want to have this field as (part of a) primary key for the table.

Use column list then and omit the PK, GUID columns
INSERT INTO TableName (col3, col4, col5, ...)
VALUES (a, b, c, d, ...) a
Using DEFAULT works around lack of column list which is best practice anyway. For example, what if you reorder or add columns? And using a trigger isn't optimal or scalable
Edit: Using a trigger is a workaround to avoid best practice... and won't scale too well

gbn is right. I'll just add a couple of other points you need to consider.
If you have a unique ID on your table, then why would you want or need a UNIQUEIDENTIFIER? You should probably choose one or the other as your PK, but not both. Also, when choosing a default for the database, choose NEWSEQUENTIALID() instead of NEWID().

It should be the Default value in the table schema. So you do not need to bother about this column after setting the default value.
Open the table design window and select the column which is supposed to occupy the GUID information. For more information, Please see below the screen shot.
So, by setting the (newID()) as a default value will let you insert the record without incorporating this column name in your insert statement.
Please let me know in case of any confusion

Related

How to make an auto-incrementing id column use missing numbers in SQL Server?

Say I have a table with 100 rows and an auto-incrementing id column, and I delete the row with id = 15. How can I add a new row with id = 15 instead of id = 101?
No, don't do it.
Generated primary keys are used to produce unique values, that are of internal use. They are not supposed to "sexy" or nice looking. That is NOT their purpose; the PK purpose is uniqueness. If you are concerned about the specific values, then it means you are exposing the PK to the external world... something that raises a lot of red flags.
If you need a value to expose, don't use the PK fot this, but create a secondary column for it. Its solely purpose in the world is to be exposed. This value can have a nice formatting with dashes (like the SSN), prefixes, suffixes, etc.
If you have a table with an identity key field you could use this:
SET IDENTITY_INSERT YourTableName ON
INSERT INTO YourTableName (ID, Other) VALUES (15, 'Whatever')
SET IDENTITY_INSERT YourTableName OFF

Adding Row in existing table (SQL Server 2005)

I want to add another row in my existing table and I'm a bit hesitant if I'm doing the right thing because it might skew the database. I have my script below and would like to hear your thoughts about it.
I want to add another row for 'Jane' in the table, which will be 'SKATING" in the ACT column.
Table: [Emp_table].[ACT].[LIST_EMP]
My script is:
INSERT INTO [Emp_table].[ACT].[LIST_EMP]
([ENTITY],[TYPE],[EMP_COD],[DATE],[LINE_NO],[ACT],[NAME])
VALUES
('REG','EMP','45233','2016-06-20 00:00:00:00','2','SKATING','JANE')
Will this do the trick?
Your statement looks ok. If the database has a problem with it (for example, due to a foreign key constraint violation), it will reject the statement.
If any of the fields in your table are numeric (and not varchar or char), just remove the quotes around the corresponding field. For example, if emp_cod and line_no are int, insert the following values instead:
('REG','EMP',45233,'2016-06-20 00:00:00:00',2,'SKATING','JANE')
Inserting records into a database has always been the most common reason why I've lost a lot of my hairs on my head!
SQL is great when it comes to SELECT or even UPDATEs but when it comes to INSERTs it's like someone from another planet came into the SQL standards commitee and managed to get their way of doing it implemented into the final SQL standard!
If your table does not have an automatic primary key that automatically gets generated on every insert, then you have to code it yourself to manage avoiding duplicates.
Start by writing a normal SELECT to see if the record(s) you're going to add don't already exist. But as Robert implied, your table may not have a primary key because it looks like a LOG table to me. So insert away!
If it does require to have a unique record everytime, then I strongly suggest you create a primary key for the table, either an auto generated one or a combination of your existing columns.
Assuming the first five combined columns make a unique key, this select will determine if your data you're inserting does not already exist...
SELECT COUNT(*) AS FoundRec FROM [Emp_table].[ACT].[LIST_EMP]
WHERE [ENTITY] = wsEntity AND [TYPE] = wsType AND [EMP_COD] = wsEmpCod AND [DATE] = wsDate AND [LINE_NO] = wsLineno
The wsXXX declarations, you will have to replace them with direct values or have them DECLAREd earlier in your script.
If you ran this alone and recieved a value of 1 or more, then the data exists already in your table, at least those 5 first columns. A true duplicate test will require you to test EVERY column in your table, but it should give you an idea.
In the INSERT, to do it all as one statement, you can do this ...
INSERT INTO [Emp_table].[ACT].[LIST_EMP]
([ENTITY],[TYPE],[EMP_COD],[DATE],[LINE_NO],[ACT],[NAME])
VALUES
('REG','EMP','45233','2016-06-20 00:00:00:00','2','SKATING','JANE')
WHERE (SELECT COUNT(*) AS FoundRec FROM [Emp_table].[ACT].[LIST_EMP]
WHERE [ENTITY] = wsEntity AND [TYPE] = wsType AND
[EMP_COD] = wsEmpCod AND [DATE] = wsDate AND
[LINE_NO] = wsLineno) = 0
Just replace the wsXXX variables with the values you want to insert.
I hope that made sense.

Copying values / columns from one table to another existing tabler in SQL Server Management Studio

I want to copy all columns from dbo.die to dbo.technology.
Both tables exist! In dbo.technology, the primary key is idTechnology
In dbo.die, the primary key is idDie and we have a foreign key, which is Technology_idTechnology in it, which connects the die table with the technology table.
How could I do that, so that the values got copied to the right rows, which match the same idTechnology?
I tried this:
INSERT INTO dbo.die
(Technology_idTechnology, Technology_D, Technology_Type, Technology_Manufacturer, Technology_SOI, Technology_Node, Technology_Name, Technology_Number_Metal, Technology_Number_Poly, Technology_Power_Cu, Technology_FEComplexity, Technology_FEComplexity_Sec, Technology_Trench, Technology_IMID, Technology_Remarks)
SELECT *
FROM dbo.technology tech
WHERE tech.idTechnology = idTechnology;
but I'm always getting an error!
Cannot insert duplicate key row in object 'dbo.die' with unique index 'ui_dieIdsample'. The duplicate key value is ().
Don't know what I should do.. I thought it's easy & simple
If a column is declared as NOT NULL (and has no default value), a value for the column must be specified in the INSERT statement.
In this specific case you should add Table2_Feld to the insert column list, and specify a value in the SELECT for it!
You will need to change your column list (lets say that its acceptable to insert a default value of 0 into column Table2_Feld)
INSERT INTO dbo.table2
(Table1_idTech, Tech_D, Techn_Type, Tech_Man,
Techn_Node, Tech_Name, Technology_Numb, Tech_Po,
Tech_FEC, Techn_Comp_Sec,
Tech_R,Table2_Feld)
select *,0 from table1 tech

Trouble with uniqueidentifier column

I just started working with SQL Server and I have some troubles with adding values to a table with a column of type uniqueidentifier.
The table consists of:
ID (uniqueidentifier), CODE (nchar(5)), COUNTRY_CODE(nchar(2)), NAME(nchar30)
I tried adding values from Excel and CSV files, basically they look like this:
DEBE,DE,Berlin
I could not load it, always have some errors with this ID field.
When i try to add values manually like:
INSERT INTO [Portfolio].[dbo].[Regions](CODE, COUNTRY_CODE, NAME)
VALUES ('DEBE', 'DE', 'Berlin');
It says:
Cannot insert the value NULL into column 'ID', table
'Portfolio.dbo.Regions'; column does not allow nulls. INSERT fails.
Of course when I add an id column and a number, I get info that int is incompatible with uniqueidentifier.
I even tried creating a temp table (with id as an INT instead of uniqueidentifier) and copying values from it into this (without ID column, its supposed to generate automatically)
Only thing I can think of is that ID column is not creating values for it automatically and I don't know how to solve this. Can anyone help?
Uniqueidentifier is a special type you can use to generate GUID. Is 16 byte long and is not incremented automatically as the Identity columns. You need to use Convert or Cast clause in order to get the correct uniqueidentifier from a varchar, if it exceeds the 16bytes it will be truncated.
Use NewID() to generate a new uniqueidentifier.
Maybe this link can help you
As mentioned above, use NewID() to create an identifier.
When you are in the design mode for the table, NewID() can be placed in the 'Default Value or Binding' slot. This means that for any new record that you insert into the table (such as CODE, COUNTRY_CODE, NAME), a Unique Identifier will be created.
What I think you are looking for is an Identity field. The UniqueIdentifier field is used for storing GUID's.
Change the field type to int and then change it's Identity Specification to 'Yes".
The other solution would be to pass the ID field your own GUID from code.
Too late to answer, but it may help someone, go to you sql table design mode,
select your required table's attribute, here in detail tab (down to table) you'll see a property
RowGuid --> Yes (make sure to turn it to yes).
Cheers :)

What the best way to self-document "codes" in a SQL based application?

Q: Is there any way to implement self-documenting enumerations in "standard SQL"?
EXAMPLE:
Column: PlayMode
Legal values: 0=Quiet, 1=League Practice, 2=League Play, 3=Open Play, 4=Cross Play
What I've always done is just define the field as "char(1)" or "int", and define the mnemonic ("league practice") as a comment in the code.
Any BETTER suggestions?
I'd definitely prefer using standard SQL, so database type (mySql, MSSQL, Oracle, etc) should't matter. I'd also prefer using any application language (C, C#, Java, etc), so programming language shouldn't matter, either.
Thank you VERY much in advance!
PS:
It's my understanding that using a second table - to map a code to a description, for example "table playmodes (char(1) id, varchar(10) name)" - is very expensive. Is this necessarily correct?
The normal way is to use a static lookup table, sometimes called a "domain table" (because its purpose is to restrict the domain of a column variable.)
It's up to you to keep the underlying values of any enums or the like in sync with the values in the database (you might write a code generator to generates the enum from the domain table that gets invoked when the something in the domain table gets changed.)
Here's an example:
--
-- the domain table
--
create table dbo.play_mode
(
id int not null primary key clustered ,
description varchar(32) not null unique nonclustered ,
)
insert dbo.play_mode values ( 0 , "Quiet" )
insert dbo.play_mode values ( 1 , "LeaguePractice" )
insert dbo.play_mode values ( 2 , "LeaguePlay" )
insert dbo.play_mode values ( 3 , "OpenPlay" )
insert dbo.play_mode values ( 4 , "CrossPlay" )
--
-- A table referencing the domain table. The column playmode_id is constrained to
-- on of the values contained in the domain table playmode.
--
create table dbo.game
(
id int not null primary key clustered ,
team1_id int not null foreign key references dbo.team( id ) ,
team2_id int not null foreign key references dbo.team( id ) ,
playmode_id int not null foreign key references dbo.play_mode( id ) ,
)
go
Some people for reasons of "economy" might suggest using a single catch-all table for all such code, but in my experience, that ultimately leads to confusion. Best practice is a single small table for each set of discrete values.
add a foreign key to "codes" table.
the codes table would have the PK be the code value, add a string description column where you enter in the description of the value.
table: PlayModes
Columns: PlayMode number --primary key
Description string
I can't see this as being very expensive, databases are based on joining tables like this.
That information should be in database somewhere and not on comments.
So, you should have a table containing that codes and prolly a FK on your table to it.
I agree with #Nicholas Carey (+1): Static data table with two columns, say “Key” or “ID” and “Description”, with foreign key constraints on all tables using the codes. Often the ID columns are simple surrogate keys (1, 2, 3, etc., with no significance attached to the value), but when reasonable I go a step further and use “special” codes. Following are a few examples.
If the values are a sequence (say, Ordered, Paid, Processed, Shipped), I might use 1, 2, 3, 4, to indicate sequence. This can make things easier if you want to find all “up through” a give stages, such as all orders that have not yet been shipped (ID < 4). If you are into planning ahead, make them 10, 20, 30, 40; this will allow you to add values “in between” existing values, if/when new codes or statuses come along. (Yes, you cannot and should not try to anticipate everything and anything that might have to be done some day, but a bit of pre-planning like this can make some changes that much simpler.)
Keys/Ids are often integers (1 byte, 2 byte, 4 byte, whatever). There’s little cost to make them character values (1 char, 2 char, 3, char, 4 char). That’s character, not variable character. Done this way, you can have mnemonics on your codes, such as
O, P, R, S
Or, Pd, Pr, Sh
Ordr, Paid, Proc, Ship
…or whatever floats your boat. Done this way, I have found that it can save a lot of time when analyzing or debugging. You still want the lookup table, for relational integrity as well as a reminder for the more obscure codes.