How to set default value in SQL server 2008? - sql-server

I have bulk amount of data stored in SQL Server 2008. Now I want to add new field [Book_ID] with default value 1 to existing table but its not working.
code
CREATE TABLE [dbo].[Ayyat_Translation_Language_old_20131209] (
[Ayat_Translation_Language_ID] INT IDENTITY (1, 1) NOT NULL,
[Translation_Laanguage_ID] INT NULL,
[Juz_ID] INT NULL,
[Surah_ID] INT NOT NULL,
[Ayat_Description] NVARCHAR (MAX) COLLATE Arabic_CI_AI_KS_WS NOT NULL,
[Ayat_No] INT NULL,
[Book_ID] INT NULL DEFAULT 1,
PRIMARY KEY CLUSTERED ([Ayat_Translation_Language_ID] ASC),
CONSTRAINT [fkey2] FOREIGN KEY ([Translation_Laanguage_ID]) REFERENCES [dbo].[Translation_Language] ([TransLation_Language_ID]) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT [fkey1] FOREIGN KEY ([Surah_ID]) REFERENCES [dbo].[Surah] ([Surah_ID]) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT [fkey0] FOREIGN KEY ([Juz_ID]) REFERENCES [dbo].[Juz] ([Juz_ID])
);
New field is added to table but it contains Null. any help!

This behavior depends on the way you insert data. If you explicitly insert NULL into the column, it will take NULL, not the default. Omit the Book_ID column out totally during an insert if you want it to take on the default (or, you can also use the keyword DEFAULT as a placeholder).
e.g. This will still insert NULL:
INSERT INTO [dbo].[Ayyat_Translation_Language_old_20131209]
(
[Ayat_Translation_Language_ID], ,
[Translation_Laanguage_ID] ,
[Juz_ID] ,
[Surah_ID] ,
[Ayat_Description] ,
[Ayat_No] ,
[Book_ID]
)
VALUES (1, 2, 3, 4, 'Foo', 5, NULL);
Whereas this will assume the default:
INSERT INTO [dbo].[Ayyat_Translation_Language_old_20131209]
(
[Ayat_Translation_Language_ID], ,
[Translation_Laanguage_ID] ,
[Juz_ID] ,
[Surah_ID] ,
[Ayat_Description] ,
[Ayat_No]
-- BOOK_ID is omitted, or use DEFAULT
)
VALUES (1, 2, 3, 4, 'Foo', 5);

You need to now alter the table to not accept NULL for Book_ID
ALTER TABLE [dbo].[Ayyat_Translation_Language_old_20131209]
ALTER COLUMN [Book_ID] INT NOT NULL DEFAULT 1
If that gives errors, you may need to update the existing records first:
UPDATE [dbo].[Ayyat_Translation_Language_old_20131209]
SET [Book_ID] = 1

Related

Inserting 2 Foreign Keys in a table in SQL Server

I have the following 3 tables. They are related:
CREATE TABLE [MemberDetails]
(
[MemberID] int identity (1000,1) NOT NULL UNIQUE,
[MName] varchar(100) NOT NULL,
[MSurname] varchar(100) NOT NULL,
[MPhone] varchar(20) NOT NULL UNIQUE,
[MEmail] varchar(200) NOT NULL UNIQUE,
[MAddress] varchar(250) NOT NULL,
[MActive] char (1) NOT NULL CHECK (MActive IN ('Y','N')) DEFAULT 'Y',
[MUpdateDate] Date NOT NULL DEFAULT GETDATE(),
[MPhoto] Image NOT NULL,
[MDid] int NULL UNIQUE,
[MTid] int NULL UNIQUE,
PRIMARY KEY ([MemberID]),
FOREIGN KEY (MDid) REFERENCES [MembershipDetails] ([MDid])
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (MTid) REFERENCES [MarketingTarget] ([MTid])
ON DELETE SET NULL
ON UPDATE CASCADE
);
CREATE TABLE [MarketingTarget]
(
[MTid] int identity (5000,1) NOT NULL UNIQUE,
[MDOB] date NOT NULL,
[MSex] char NOT NULL CHECK (MSex IN ('M','F')) DEFAULT 'M',
PRIMARY KEY ([MTid]),
);
CREATE TABLE [MembershipDetails]
(
[MDid] int identity (2000,1) NOT NULL UNIQUE,
[MType] varchar(10) NOT NULL CHECK (MType IN ('Monthly', 'Quaterly', 'Yearly')) DEFAULT 'Monthly',
[JoinDate] Date NOT NULL DEFAULT GETDATE(),
[ExpiryDate] Date NULL,
[MsUpdateDate] Date DEFAULT GETDATE(),
PRIMARY KEY ([MDid])
);
I would like to know if it's possible to insert the FKs automatically into the MemberDetails table from the other two tables? I am trying to write the Stored Procedures.
I was checking the Scope_Identity which can get the last identity generated but I am not sure how to use it properly.
Any suggestions would be much appreciate it.
Here is an example (table has been shortened): Since both IDENTITY values are required, I'd save them into a variable and then insert together into MemberDetail.
I would recommend to have a transaction for this operation. And have a look at TRY..CATCH. Depending on your situation you might want to check XACT_STATE().
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/try-catch-transact-sql?view=sql-server-ver15
and there are examples using a trigger
https://learn.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql?view=sql-server-ver15
CREATE TABLE [_TEST_MemberDetails] (
[MemberID] int identity (1000,1) NOT NULL UNIQUE,
[MDid] int NULL UNIQUE,
[MTid] int NULL UNIQUE,
PRIMARY KEY ([MemberID]),
FOREIGN KEY (MDid) REFERENCES [_TEST_MembershipDetails] ([MDid]) ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (MTid) REFERENCES [_TEST_MarketingTarget] ([MTid]) ON DELETE SET NULL
ON UPDATE CASCADE
);
CREATE TABLE [_TEST_MarketingTarget] (
[MTid] int identity (5000,1) NOT NULL UNIQUE,
[MDOB] date NOT NULL,
[MSex] char NOT NULL CHECK (MSex IN ('M','F')) DEFAULT 'M',
PRIMARY KEY ([MTid]),
);
CREATE TABLE [_TEST_MembershipDetails] (
[MDid] int identity (2000,1) NOT NULL UNIQUE,
[MType] varchar(10) NOT NULL CHECK (MType IN ('Monthly','Quaterly','Yearly')) DEFAULT 'Monthly',
[JoinDate] Date NOT NULL DEFAULT GETDATE(),
[ExpiryDate] Date NULL,
[MsUpdateDate] Date DEFAULT GETDATE(),
PRIMARY KEY ([MDid])
);
-- SP CODE START HERE
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION
DECLARE #MTID int = 0, #MDID int = 0
INSERT INTO _TEST_MarketingTarget ([MDOB], [MSex])
VALUES ('Jan 1, 2020', 'M')
SELECT #MTID = SCOPE_IDENTITY()
INSERT INTO [_TEST_MembershipDetails] ([MType], [JoinDate], [ExpiryDate], [MsUpdateDate])
VALUES (DEFAULT, DEFAULT, 'Jan 1, 2020', DEFAULT)
SELECT #MDID = SCOPE_IDENTITY()
INSERT INTO [_TEST_MemberDetails] (Mdid, MTid)
SELECT #MDID, #MTID
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF ##TRANCOUNT <> 0 ROLLBACK TRANSACTION
END CATCH
go

Creting FOREIGN KEY constraint on multiple columns with one of them being constant value

When I have table with PRIMARY KEY from 2 columns:
CREATE TABLE SizeTypes
(
TypeID tinyint NOT NULL,
SizeID tinyint NOT NULL,
Name varchar(100) NOT NULL,
CONSTRAINT PK_SizeType
PRIMARY KEY (TypeID, SizeID)
)
How can I create second table with a foreign key that have 1st constant value and 2nd from column like below:
CREATE TABLE Something
(
ID INT IDENTITY(1,1) PRIMARY KEY,
SizeTypeID_1 TINYINT,
SizeTypeID_2 TINYINT,
SizeTypeID_3 TINYINT,
CONSTRAINT FK_Something_SizeTypes_1
FOREIGN KEY (1, SizeTypeID_1)
REFERENCES SizeTypes(TypeID, SizeID),
CONSTRAINT FK_Something_SizeTypes_2
FOREIGN KEY (2, SizeTypeID_2)
REFERENCES SizeTypes(TypeID, SizeID),
CONSTRAINT FK_Something_SizeTypes_3
FOREIGN KEY (3, SizeTypeID_3)
REFERENCES SizeTypes(TypeID, SizeID)
)
This can be done using FOREIGN KEY, if yes then how?
If no then what other ways to do this I have? Triggers on INSERT and UPDATE for table something and on DELETE for table SizeTypes? Any other choices I have?
It looks like the following code will let you create suitable check constraints with the check implemented by a separate function:
-- Create the first table.
create table SizeTypes(
TypeId TinyInt not NULL,
SizeId TinyInt not NULL,
Name VarChar(100) not NULL,
constraint PK_SizeType primary key ( TypeId, SizeId ) );
go
-- Create a function to implement the logic for the check constraint.
create function CheckSizeTypeId(
#TypeId TinyInt, #SizeId TinyInt )
returns Int
as begin
-- Replace the following statement with the logic for your check.
if #SizeId >= 0 and #SizeId <= ( select SizeId from SizeTypes where TypeID = #TypeID )
return 1;
return 0;
end;
go
-- Create the second table with the check constraints.
create table Something(
Id Int identity(1,1) primary key,
SizeTypeId_1 TinyInt,
SizeTypeId_2 TinyInt,
SizeTypeId_3 TinyInt,
constraint Check_SizeTypeId_1 check ( dbo.CheckSizeTypeId( 1, SizeTypeId_1 ) = 1 ),
constraint Check_SizeTypeId_2 check ( dbo.CheckSizeTypeId( 2, SizeTypeId_2 ) = 1 ),
constraint Check_SizeTypeId_3 check ( dbo.CheckSizeTypeId( 3, SizeTypeId_3 ) = 1 ) );
go
-- Houseclean.
drop table SizeTypes;
drop table Something;
drop function CheckSizeTypeId;
Note that the constraints restrict what you can do with values in Something. Changes in SizeTypes will not revalidate data in Something, though that could be implemented in a trigger on SizeTypes.

WPF Cant insert into table - (I AM NOT SETTING VALUE INTO IDENTITY COULMN)

THIS IS NOT DUPLICITY
I am NOT setting value to identity column!
I cant add value in my Table. I think all set good but this error keeps comming:
"Cannot insert explicit value for identity column in table 'MainQueue'
when IDENTITY_INSERT is set to OFF."
My table:
CREATE TABLE [dbo].[MainQueue] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Created] DATETIME NOT NULL,
[IdOffice] INT NOT NULL,
[IdCategory] INT NOT NULL,
[StartProcessTime] DATETIME NULL,
[EndProcessTime] DATETIME NULL,
[IdUser] INT NULL,
[Sms] BIT CONSTRAINT [DF__MainQueue__Sms__412EB0B6] DEFAULT ((0)) NOT NULL,
[OrderNumber] INT NOT NULL,
[IdSms] INT NULL,
[UserWindowNumber] INT NULL,
CONSTRAINT [PK__MainQueu__3214EC0783954F32] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_MainQueue_Category] FOREIGN KEY ([IdCategory]) REFERENCES [dbo].[Category] ([Id]),
CONSTRAINT [FK_MainQueue_Office] FOREIGN KEY ([IdOffice]) REFERENCES [dbo].[Office] ([Id]),
CONSTRAINT [FK_MainQueue_User] FOREIGN KEY ([IdUser]) REFERENCES [dbo].[User] ([Id]),
CONSTRAINT [FK_MainQueue_SmsQueue] FOREIGN KEY ([IdSms]) REFERENCES [dbo].[SmsQueue] ([Id])
);
My code for adding:
var queueItem = new MainQueue();
queueItem.IdOffice = officeId;
queueItem.IdCategory = categoryId;
queueItem.Created = DateTime.Now;
queueItem.OrderNumber = orderNum;
dc.MainQueues.InsertOnSubmit(queueItem);
dc.SubmitChanges();
THIS IS NOT DUPLICITY
I am NOT setting value to identity column!
Your described ID column is an autoincrement identity column, that means you cannot pass any explicit value for the ID, after an insert the DBS will do fill the ID. Remove the ID column in your Insert method and do not pass a parameter for the Id when calling your method.
If you really need to insert an explicit value for the ID, either make the column not an IDENTITY, instead primary or turn IDENTITY INSERT OFF before you call the insert and turn in back on afterwards.

Insert new record with composite primary key, which consists of two foreign keys from different tables

Please help me figure out how to Insert new record with composite primary key, which consists of two foreign keys from different tables.
I am working in C#, WPF if that matters.
I have three tables: Sales, SaleItem, Item.
CREATE TABLE [dbo].[Sales] (
[saleID] INT IDENTITY (1, 1) NOT NULL,
[saleTime] DATETIME NOT NULL,
[customerID] INT NULL,
[TIN] INT NOT NULL,
CONSTRAINT [PK_Sales] PRIMARY KEY CLUSTERED ([saleID] ASC),
CONSTRAINT [FK_Sales_Customers] FOREIGN KEY ([customerID]) REFERENCES [dbo].[Customers] ([customerID]),
CONSTRAINT [FK_Sales_Company] FOREIGN KEY ([TIN]) REFERENCES [dbo].[Company] ([TIN])
);
CREATE TABLE [dbo].[Item] (
[ItemSKU] INT IDENTITY (1, 1) NOT NULL,
[itemName] NVARCHAR (50) NOT NULL,
[volume] FLOAT (53) NOT NULL,
[measureUnit] NVARCHAR (50) NOT NULL,
[producer] NVARCHAR (50) NOT NULL,
[supplierID] INT NOT NULL,
[retailPrice] NUMERIC (18) NOT NULL,
CONSTRAINT [PK_Item] PRIMARY KEY CLUSTERED ([ItemSKU] ASC),
CONSTRAINT [FK_Item_Suppliers] FOREIGN KEY ([supplierID]) REFERENCES [dbo].[Suppliers] ([supplierID])
);
CREATE TABLE [dbo].[SaleItem] (
[saleID] INT IDENTITY (1, 1) NOT NULL,
[itemSKU] INT NOT NULL,
[quantity] INT NOT NULL,
CONSTRAINT [PK_SaleItem] PRIMARY KEY CLUSTERED ([saleID] ASC, [itemSKU] ASC),
CONSTRAINT [FK_SaleItem_Sales] FOREIGN KEY ([saleID]) REFERENCES [dbo].[Sales] ([saleID]),
CONSTRAINT [FK_SaleItem_Item] FOREIGN KEY ([itemSKU]) REFERENCES [dbo].[Item] ([ItemSKU])
);
I want to insert a new record into SaleItem table (the third one) where saleID is the last ID recorded in Sales table and ItemSKU which is equal to the value I get from another window.
I want these values:
SaleID = SELECT TOP 1 saleID FROM Sales ORDER BY saleID DESC";
ItemSKU = "SELECT itemName FROM Item WHERE ItemSKU = #sku";
I think I must do it in one query but I have no idea how.
Can you please give me a hint? I
First, you need to remove the IDENTITY property from the dbo.SaleItem table. The IDENTITY property is only required on the parent table, dbo.Sales.
You can do a single INSERT statement like this. It uses two subqueries, which are the SELECT statements in parentheses, to get values from the other two tables.
INSERT INTO dbo.SaleItem (saleID, itemSKU, quantity)
VALUES ((SELECT MAX(saleID) FROM dbo.Sales),
(SELECT ItemSKU FROM dbo.Item WHERE itemName = N'Widget'),
50);
You might want to turn it into a stored procedure, like this:
CREATE PROCEDURE dbo.up_InsertSaleItem
(
#itemName nvarchar(50),
#quantity int
)
AS
INSERT INTO dbo.SaleItem (saleID, itemSKU, quantity)
VALUES ((SELECT MAX(saleID) FROM dbo.Sales),
(SELECT ItemSKU FROM dbo.Item WHERE itemName = #itemName),
#quantity);
Then to use the stored procedure:
-- Test the stored procedure
EXEC dbo.up_InsertSaleItem #itemName=N'Widget', #quantity=50;
SELECT *
FROM dbo.SaleItem;
To read more about subqueries, see Microsoft SQL Server 2012 T-SQL Fundamentals by Itzik Ben-Gan, Chapter 4: Subqueries.

Inserting into a table to by pass constraints

maybe I can get some feedback from some folks on this. I created two tables and inserted data into one table and i put a constraint (Foreign key) on the table std_individual_address.
I get the following error message when I try to execute the insert now:
Msg 515, Level 16, State 2, Line 43 Cannot insert the value NULL into
column 'individual_GUID', table 'ABLE.dbo.std_individual_address';
column does not allow nulls. INSERT fails. The statement has been
terminated.
Here is all my code:
--Create the std_individual table
CREATE TABLE std_individual(
individual_GUID INT NOT NULL IDENTITY,
individual_First_Name VARCHAR(50) NULL,
individual_Last_Name VARCHAR(50) NULL,
individual_email VARCHAR(40) NULL,
PRIMARY KEY (individual_GUID));
--Create the std_individual_address table
CREATE TABLE std_individual_address
(
individual_address_GUID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
individual_address_line1 VARCHAR(100) NULL,
individual_address_line2 VARCHAR(100) NULL,
individual_address_line3 VARCHAR(100) NULL,
individual_address_city VARCHAR(50) NULL,
individual_address_state VARCHAR(30) NULL,
individual_address_zipcode VARCHAR(30) NULL,
individual_GUID INT NOT NULL,
CONSTRAINT fk_std_individual_address_std_individual FOREIGN KEY (individual_GUID) REFERENCES std_individual (individual_GUID)
)
--Insert Individual Data
INSERT INTO std_individual
(individual_First_Name,individual_Last_Name,individual_email)
VALUES
('Terry','Smith','tsmith#example.net'),
('Ronald','Smegan','ronald#example.net'),
('Arnold','Aggassi','aaggassi#example.edu'),
('Jerry','Brukheimer','bbrukheimer#example.edu');
--Mind the Constraint
INSERT INTO std_individual_address(individual_GUID) SELECT individual_GUID from std_individual
--Attempt to insert rest of the data
INSERT INTO std_individual_address
(individual_address_line1,individual_address_line2,individual_address_city,individual_address_state,
individual_address_zipcode )
VALUES
('8200 Greensboro Drive','Ste 1500','Mclean','Virgina','22102'),
('1121 14th Street, NW','Ste 1000','Washington' ,'District of Columbia','20005'),
('1700 Connecticut Ave,NW','Ste 300','Washington' ,'District of Columbia','20009'),
('205 Pennsylvania Ave,SE','','Washington','District of Columbia','20003');
Then I get the error message above. Any ideas on how to combat that issue?

Resources