SQL Server Best Practices Table Linking - sql-server

I am new to SQL server and am wanting to make sure I am using best practices. What I am doing is creating 7 tables.
(Transaction,Customer,Business,Vehicle,Seller,Lien,Mailto)
Transaction is my main table where it creates a TransactionID. Then in the other 6 tables I will also have a TransactionID column so I can link them all together.
In the other 6 tables they each have there own ID as well.
For example
(CustomerID, BusinessID, VehicleID, SellerID, LienID, MailtoID)
My question is in my transaction table do I have to list all of those IDs or does having just the TransactionID allow them all to connect.
Transaction Table 1 Example
ID
Type
DateTime
Transaction Table 2 Example
ID
Type
CustomerID
BusinessID
VehicleID
MailtoID
SellerID
LienID
DateTime
(For the transaction ID I am wanting it to be created and then automatically fill the same in for the other tables as those fields are submitted using foreign keys I believe)
Any help on this would be greatly appreciated!!

do I have to list all of those IDs- NO!.
having just the "TransactionID" allow them all to connect.

Related

Identity column in a budget table

Programming noob here, and DBA I am not..
I am creating a table called 'budget' on a 2005 sqlserver databases. The purpose of this table is to simply store the monthly $ allowed to departments for budgeting purposes.
The essential columns in this table will be month, year, dept, amount. I am migrating this from an old foxpro table which did not have an identity/primary key column.
My question is, for my purposes do I need to worry about creating an identity column? I am having a hard time importing the data into SQLserver and having it populate the ID column, so I am inclined to just skip it if it's not needed. Thanks for your $.02
If you're specifying a PK in your insert statement, you'll need to use SET IDENTITY_INSERT <tableName> ON at the beginning of your query.
For more information, look here.

Transfer data from one database to another database with different schema

i have problem to Transfer data from one sqlserver 2008 r2 to another sql server 2012 databases with different schema, here is some different scenario,
database 1
database 1 with tables Firm and Client, these both have FirmId and ClientId primary key as int datatype,
FirmId is int datatype as reference key used in Client table.
database 2
database 2 with same tables Firm and Client, these both have FirmId and ClientId but primary key as uniqueidentifier,
FirmId is uniqueidentifier datatype as reference key used in Client table.
problem
the problem is not to copy data from 1 database table to 2 database table, but the problem is to maintain the reference key's Firm table into Client table. because there is datatype change.
i am using sql server 2008 r2 and sql server 2012
please help me to resolve / find the solution, i really appreciate your valuable time and effort. thanks
I'll take a stab at it even if I am far from an expert on SQLServer - here is a general procedure (you will have to repeat it for all tables where you have to replace INT with UID, of course...).
I will use Table A to refer to the parent (Firm, if I understand your example clearly) and Table B to refer to the child (Client, I believe).
Delete the relations pointing to Table A
Remove the identity from the id column of Table A
Create a new column with Uniqueidentifier on Table A
Generate values for the Uniqueidentifier column
Add the new Uniqueidentifier column in all the child tables (Table B)
Use the OLD id column to map your child record & update the new Uniqueidentifier value from your parent table.
Drop all the id columns
Recreate the relations
Having said that, I just want to add a warning to you: converting to UID is, according to some, a very bad idea. But if you really need to do that, you can script (and test) the above mentioned procedure.

Need some suggestions for database design for Invoices in a multi-tenant app

I need some guidance on designing the schema for invoices in a multi-tenant application.
I have a table called EmployeePay which holds all the information required to generate an invoice. The invoice table would have the invoice number, invoice created date and VAT rate. I am thinking to create a Sequence object for each Tenant to generate an invoice number.
EmployeePay Table: EmployeeID, Hours, Rate, InvoiceID (FK)
Invoice Table: InvoiceID (PK) (Identity), InvoiceNumber, InvoiceDate, VATRate, TenantID
Is it okay to have hundreds of Sequence objects in a database, as I’ll have to create one for each tenant? I’ll also have to create same amount of stored procedures which returns the next invoice number (I prefer a separate stored procedure for each tenant rather than having one large stored procedure with hundreds of choices in a select case statement).
Another concern is, is it theoretical to insert into the master table (Invoice) based on the transaction table (EmployeePay) and then use its primary key(InvoiceID) to update the transaction table?
Thanks in advance.
First make sure the relationship either this is one to many or many to many. If you are considering one employee that will have many invoices then its one to many relationship and you can create your table as under:
EmployeePay Table: EmployeeID (PK) (Identity), Hours, Rate
Invoice Table: InvoiceID (PK) (Identity), EmployeeID (FK), InvoiceNumber, InvoiceDate, VATRate, TenantID
EDIT:
I don't know which database you are using but for increment sequence check:
for MySQL check this LINK.
If you are using Oracle then check this LINK
I would suggest you to create another table can be called as InvoiceNumber, this will contain InvoiceNumberId(Int),TenantId (Fk), CurrentSequenceNumber(Int).
Significance of CurrentSequenceNumber is that it will be simple integer number which can be used to generate next Invoicenumber.InvoiceNumberId will be a Identity columns for Primary key purpose (you may or may not have it).
Structure of the Table will look like below.
Now you need to create only One Stored Procedure which will take input parameter as TenantId and will have responsiblity to generate next Invoice number by reading CurrentSequenceNumber from above table.
For example if we need to generate new Invoice Id for Tenant with id as 15 then SP will have your Business logic I am assuming Just creating a String with "Inv-" as prefix with incremented value of CurrentSequenceNumber so output of Procedure will be.
Inv-0009
Then after generation of this number SP will increment value to 9 for InvoiceNumberId 3.
So everything will be managed by Single table and Single procedure only.

SQL Server : restore from backup but keep ID (identity) references

I have the following scenario. Let's say I have 3 tables:
IDs are integers and primary key with identity(1,1).
Clients (ID (pk), Name)
Orders (ID (pk), ClientID (fk), Date)
OrderDetails (ID (pk), OrderID (fk), Product, Quantity, Price)
Let's say I accidentally deleted all records from those 3 tables, but I have a DB backup. The question is how do I reinsert those deleted records from backed up DB into the current DB?
I know I can simply "set identity_insert on" and use "insert into", but is a web application and it must stay alive and there are inserts from users going on.
If I insert all Clients back, their ID will be different and Orders(ClientID) cannot refers to that anymore. So on with Orders/OrderDetails tables.
I need some way to update the foreign key ids with new ones. How can I do that?
Some kind of temp tables to keep records of old IDs and new IDs?
Hope that I made my question clear :)
If it were me, I'd:
Determine which rows are in your backup that aren't in your live database
Insert the rows from your backup into your live database with a value of -1 * identity value. For instance, if the row was in the backup with a identity value of 1234, you'd insert it into your live database with an identity value of -1234. This goes not only for identity values, but for any rows that reference those values (i.e. foreign keys).

Microsoft SQL server: have one auto-incrementing column update another table

I have a table of orders with orderID. I want when I create a new row in orders, and automatically have it add the same orderID to a new row in orderDetails. I got the auto incrementing to work, however whenever I try to link the two, adding cascade delete, it gives me an error.
'order' table saved successfully
'orderDetail' table
- Unable to create relationship 'FK_orderDetail_order'.
Cascading foreign key 'FK_orderDetail_order' cannot be created where the referencing column 'orderDetail.orderID' is an identity column.
Could not create constraint. See previous errors.
Which seems to be because of the fact there is no orderID at row creation. Without these two linked it's pretty hard to link an order to its information.
I am using Microsoft SQL server mgt studio. I learned via command-line MySQL, not SQL, so this whole GUI stuff is throwing me off (and I'm a tad rusty).
Your problem is that 'orderDetail.orderID' should not be an identity column (auto-incrementing). It should be based on the orderId in the Order table. You can do that in a variety of ways. If you are using stored procedures, and making separate calls to the database for the orderDetail records, have the code save the order row first, and return the newly created OrderId value, then use that value on the calls to save orderdetails. If you are making one call to a stored proc that saves the order header record and all order detail records in one call, then in the stored procd, insert the ordfer record forst, use Scope_identity() to extract the newly created orderId into a T-SQL variable,
Declare #orderId Integer
Insert Orders([Order table columns])
Values([Order table column values])
Set #orderId = scope_Identity()
and then use the value in #orderId for all inserts into the OrderDetails table...
Insert OrderDetails(OrderId, [Other OrderDetail table columns])
Values(#orderId , [Other OrderDetail table column values])
You want a AFTER INSERT trigger on the order table - in this, the newly given ID is available as NEW.orderID and can now easily be inserted into orderDetails.
Just do this via the command line. I certainly do.

Resources