SQL 2012 :: How To Add A Table Constraint That Will Only Accept Values Y Or N
Oct 21, 2015Create table enrollment_in
BEN_DENT VARCHAR(1)
What I need is a constraint to limit the values to Y or N
Create table enrollment_in
BEN_DENT VARCHAR(1)
What I need is a constraint to limit the values to Y or N
I am relatively new to SQL and as a project I have been asked to create the SQL for a simple database to record train details. I want to implement a check constraint which will prevent data from being inserted into a table if the weight of the train is more than the maximum towing weight of the locomotive. FOr instance, I need to add the unladen weight and maximum capacity of each wagon (located in the wagon type table) and compare it against the locomotive maximum pulling weight (the locomotive class table). I have the following SQL but it will not work:
check((select SUM(fwt.unladen_weight+fwt.maximum_payload) from
hauls as h,freight_wagon as fw,freight_wagon_type as fwt,train as t where
h.freight_wagon_serial_number = fw.freight_wagon_serial_number and
fw.freight_wagon_type = fwt.freight_wagon_type and
h.train_number = t.train_number) <
(select lc.maximum_towing_weight from locomotive_class as lc,locomotive as l,train as t where
lc.locomotive_class = l.locomotive_class and l.locomotive_serial_number = t.locomotive_serial_number))
The hauls table is where the constraint has been placed and is the intermediary table between train and freight wagon.
I may not have explained this very well; but in short, i need to compare the sum of two values in one table against a values located in another table...At present I keep getting a message telling me the sub query cannot return more than one row.
I am trying to have a query with the option for items to be null. (So users don't need to fill in the other fields if they choose not too) SELECT Tickets.TicketID, Tickets.UserID, Tickets.SystemID, Tickets.Title, Tickets.Description, Tickets.Software, Tickets.Date, Systems.OS, OS.OS AS OstitleFROM Tickets INNER JOIN Systems ON Tickets.SystemID = Systems.SystemID INNER JOIN OS ON Systems.OS = OS.osIDWHERE (Tickets.Title LIKE '%' + @title + '%') AND (Tickets.Software LIKE '%' + @software + '%') AND (Tickets.Description LIKE '%' + @descrip + '%') AND (Systems.OS = @osid) OR (@osid IS NULL)This works when i give the LIKE values % as a parameter. So they can choose to search by title + software but not description or description and nothing else etc etc etc. The problem is, the osid. If I give it a value it works but if i try to do null, *. or % it always displays every item in the databse ignoring any of the previous like statements. Anyone have an idea?
View 3 Replies View RelatedFriends,
I am inserting a value from vb.net to sql server 7.
i created a table in the sqlserver with primary key.
In VB.net form i didnt check the values of the check box.
when i try to save the empty or null the sql server should throw the error. but its accepting the null value.
how is it possible?
can anyone help me?
FYI:
table name: JobMast
Fields:
jobcode int primary key
jobtitle varchar(10)
Select MemberNbr, EligYear,EligMonth, count(*) FROM [MemberMonth]
GROUP BY MemberNbr, EligYear,EligMonth HAVING COUNT(*) > 1
THIS WILL GIVE ME ZERO ROWS,,, That is GOOD which means NO DUPLICATES..I need to add a constraint to the table MEMBERMONTH to make sure no one can insert duplicate records.
MemberNbr VARCHAR,
EligYear INT ,
EligMonth INT
I have a table that lists math Calculations with "User Friendly Names" that look like the following:
([Sales Units]*[AUR])
([Comp Sales Units]*[Comp AUR])
I need to replace all the "User Friendly Names" with "System Names" in the calculations, i.e., I need "Sales Units" to be replaced with "cSalesUnits", "AUR" replaced with "cAUR", "Comp Sales Units" with "cCompSalesUnits", and "Comp AUR" with "cCompAUR". (It isn't always as easy as removing spaces and added 'c' to the beginning of the string...)
The new formulas need to look like the following:
([cSalesUnits]*[cAUR])
([cCompSalesUnits]*[cCompAUR])
I have created a CTE of all the "Look-up" values, and have tried all kinds of joins, and other functions to achieve this, but so far nothing has quite worked.
How can I accomplish this?
Here is some SQL for set up. There are over 500 formulas that need updating with over 400 different "look up" possibilities, so hard coding something isn't really an option.
DECLARE @Synonyms TABLE
(
UserFriendlyName VARCHAR(128)
, SystemNames VARCHAR(128)
)
INSERT INTO @Synonyms
( UserFriendlyName, SystemNames )
[Code] .....
Table ATable B
AIDBID
Col 1BCol1
Col 2
Col3
I want to put a check constraint on A.col3 that depends on the values of A.Col1, A.Col2 and B.BCol1
How can I achieve this without using function.
After reading all the comments about microsoft ole db provider for db2, I've started converting a project from ibm db2 provider to microsoft ole db provider, for the reason that the server would not need a ibm client software installation anylonger.
However in one of the dataflows there is a select statement on the DB2 database (AS400 iseries DB2 V5R4) that uses common table expression. The Oledb data source in the Dataflow returns zero input columns when I use the microsoft provider instead of the ibm provider. When I set it back to use the ibm oledb provider the input columns are available again.
The common table expression is used in the select statement like:
WITH x AS (SELECT ... FROM mytable WHERE ...)
SELECT x.*, (x.a - x.b) As diff
FROM x
We are not allowed to change anything in the DB2 database, so using views or sprocs is not an option.
Did anyone else experience this and can it be avoided without changing the selct logic?
I have a table-valued function in mssql 2005 as below:
ALTER FUNCTION fn_test{ @test nvarchar(1000)}RETURNS@TEMP TABLE{ test nvarchar(1000)}ASBEGIN INSERT INTO @TEMP SELECT @test
RETURNEND
Everytime, I passed in chinese character (@test), such as 測驗, the function will return ????. What should I do for the table-valued function, so that the chinese character can be passed in? Please help.
Note: I can search and get the chinese characters if I use stored procedures; and the columns in the tables can store chinese chararcters as well. Only table-valued function is not working with the chinese characters. Is it a bug from MSSQL 2005?
I'm looking for a script that identifies max values used in a table for all smallints, ints and bigints to determine if they are being used correctly.
View 3 Replies View RelatedI know how to check for a sinle vlaue but how do I chekc to see if multiple values exist. I need to check for certain email addresses from a list that I have.
Let us say I ahve 3 email addresses, I want to check for all of them in a table and for eevery email address that is present I want to print something like "You email address is XXX" and if one of those 3 is not found my results should look like
"You email address is XXX"
YYYYY not found
"You email address is ZZZZ"
I'm attaching some TSQL that I tried on [AdventureWorks2012].[Person].[EmailAddress]
/****** Select ALL if where an email address is present in the list ******/
SELECT EmailAddressID,EmailAddress
FROM [AdventureWorks2012].[Person].[EmailAddress]
WHERE EmailAddress IN
(
'ken0@adventure-works.com', --1
'terri0@adventure-works.com', --2
[Code] ....
-- Test to see if a single email address is present
IF EXISTS
(
SELECT EmailAddress FROM [AdventureWorks2012].[Person].[EmailAddress]
WHERE EmailAddress IN ('25rob0@adventure-works.com')
)
BEGIN
SELECT 'Email address is presnt'
[Code] ....
When I check multiples using EXISTS it works as per its design and says YES even if a single item is present.
I have 3 table
table_A
table_B
table_C
TABLE_A
SNO NAME ID
1 RAJU 070491
2 VAMSHI 089767
3 ARUNA 068908
TABLE_B
SNO NAME ID
2 RAJU 070491
4 JKLKJ 098766
I WANT COMPARE TWO TABLES(TABLE_A & TABLE_B) SELECT TABLE_A MATCHING VALUES COPY IN TABLE_C
EX-
SNO NAME ID
1 RAJU 070491
I'd like to create a table that will store different order items. Several order items make up one single order. Order items can have 0 or more children (max depth will never be deeper than one). Order items can have up to 150 attributes/values. The way I think this should be done is using XML column instead of the EAV type of model. My table structure currently looks like this:
* child_order_item_id (PK)
* parent_order_item_id (FK to child_order_item_id)
* order_id (FK to Order table)
* product_id (FK to Product table)
* price
* attribute_XML
How my attribute_XML should look like or how to validate the xml.
I am trying to create a check command that ensures only A'B','c','D','E','F','G and s1, s2 can be inserted in the table, is this even applicable? Heres my code:
Create Table GRADE (
GradeVARCHAR2(1) CONSTRAINT pk_Grade PRIMARY KEY
CONSTRAINT check_grade
CHECK (substr(Grade = 'A','B','c','D','E','F','G')),
Salary_Scale VARCHAR2(2) CONSTRAINT check_SScale
CHECK (substr(Salary_Scale = 'S1', 'S2')),
)
/
I am trying to insert values in a single table with four columns from 4 different sources. is it possible to run these 4 insertions in parallel. all these insertion are independent of each other
View 3 Replies View RelatedI have a table that has the following structure:
EntryID int,
Categories varchar(200)
values look like:
541,'A,B,C'
345,'B,C'
234,'A,C'
657,'D,E'
435,'D'
what I want to do is extract the Categories column to a normalized separate table:
541,'A'
541,'B'
541,'C'
345,'B' ....
I found the split using the tally table useful to split one-by-one, but how can it be applied when you are referring to a table?
I have a table with PO#,Days_to_travel, and Days_warehouse fields. I take the distinct Days_in_warehouse values in the table and insert them into a temp table. I want a script that will insert all of the values in the Days_in_warehouse field from the temp table into the Days_in_warehouse_batch row in table 1 by PO# duplicating the PO records until all of the POs have a record per distinct value.
Example:
Temp table: (Contains only one field with all distinct values in table 1)
Days_in_warehouse
20
30
40
Table 1 :
PO# Days_to_travel Days_in_warehouse Days_in_warehouse_batch
1 10 20
2 5 30
3 7 40
Updated Table 1:
PO# Days_to_travel Days_in_warehouse Days_in_warehouse_batch
1 10 20 20
1 10 20 30
1 10 20 40
2 5 30 20
2 5 30 30
2 5 30 40
3 7 40 20
3 7 40 30
3 7 40 40
How can I update Table 1 to see desired results?
I am having problems displaying time values in my SSRS report. below is info. Tried expressions still does not work. I want the values to show what in the SQL Server table 00:00:00.82. I tried stored proc still does not work.
SQL Server table time value shown in milliseconds:
00:00:00.82
Reporting Services report value shown:
00:00:00
The objective is to identify orders where an order fee has been applied incorrectly. I have multiple orders per customer, my table contains an orderID and a customerID. Currently if the customer places additional orders before the previous orders have been closed/cancelled, then additional fees are being applied.
Let's say I'm comparing order #1 to order #2. I need to identify these rows where the following is true:-
The CustID is the same.
Order #2 has a more recent order date.
Order #2 has a FeeDate Before the CancelledDate of Order #1 (or Order #1 has no cancellation date).
So in the table the orderID:2835692 of CustID: 24643 has a valid order fee. But all the subsequently placed orders have fees which were applied before the first order was cancelled and so I want to update the FeeInvalid column with a 'Y'. The first fee will always be valid.
I think I understand why the code I am trying doesn't achieve the result I want but I can't figure out how to write it correctly. Below is one example of code I've tried and also code to create the table and insert some test data.
update t1
SET FeeInvalid = 'Y'
FROM MockData t1 Join MockData t2 on t1.CustID = t2.CustID
WHERE t1.CustID = t2.CustID
AND t2.OrderDate > t1.OrderDate
AND t2.FeeDate > t1.CancelledDate
CREATE TABLE [dbo].[MockData](
[OrderID] [float] NULL,
[code]....
I am trying to merge records with a stored procedure and I am getting a constraint violation error. Just wondering is there a way of finding out which records are the actual culprit?
This would help greatly in being able to troubleshoot this issue.
The error is this:
2/21/2008 12:40:39 PM :: Violation of UNIQUE KEY constraint 'SK_SomeConstraint'. Cannot insert duplicate key in object 'tblTable'.
The statement has been terminated.
The constraint is a group of clustered indexes that must be unique:
GO
/****** Object: Index [SK_SomeConstraint] Script Date: 04/11/2008 14:56:17 ******/
ALTER TABLE [dbo].[tblTable] ADD CONSTRAINT [SK_SomeConstraints] UNIQUE NONCLUSTERED
(
[IDa] ASC,
[IDb] ASC,
[IDc] ASC,
[someField] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
After adding a Unique constraint to a database I cannot add more than one record with a null value for the constrained field. I've tried both adding the constraint to an empty table as well as a table with multiple null values already in the subject field; both efforts have failed.
According to BOL SQL-7 allows Unique Constraints on fields with Null values. Am I missing a step? I do need to allow nulls in the field yet ensure that when there is a non-null value it is unique.
The SQL statement I've used is: ALTER TABLE tbl_MasterUIC ADD CONSTRAINT uniquesamplenbr UNIQUE NONCLUSTERED (samplenbr)
Thanks for any and all suggestions
Why we the Unique Constraint doesn't allow the multiple null values in Sql Server?
View 2 Replies View RelatedI have 2 identical tables one contains current settings, the other contains all historical settings.I could create a union view to display the current values from table A and all historical values from table B, butthat would also require a Variable to hold the tblid for both select statements.
Q. Can this be done with one joined or conditional select statement?
DECLARE @tblid int = 501
SELECT 1,2,3,4,'CurrentSetting'
FROM TableA ta
WHERE tblid = @tblid
UNION
SELECT 1,2,3,4,'PreviosSetting'
FROM Tableb tb
WHERE tblid = @tblid
Got the following error when the backup was run
Executing the query "BACKUP DATABASE [msdb] TO DISK = N'd:Sql backups..." failed with the following error: "Violation of PRIMARY KEY constraint 'PK__backupse__21F79AAB7WERB85D3'. Cannot insert duplicate key in object 'dbo.backupset'. The duplicate key value is (16771).Could not insert a backup or restore history/detail record in the msdb database. This may indicate a problem with the msdb database. The backup/restore operation was still successful.
12 percent processed.
21 percent processed.
31 percent processed.
41 percent processed.
[code]...
The statement has been terminated.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Running an insert into a table where a column has a constraint for unique records
i have an autonumber pk that increments but numbers are not in sequence etc. if constraints are found
e.g.
10 records are inserted but only 2 are unique but there is a gap of 8 in the PK autoincrement value (it's like the unique records that were not inserted are still being recorded by the autoincrement).
I've got some records like this:
ID_________Jan Feb...........................Dec
0000030257 0 0 0 0 0 0 1 1 1 1 1 0
where each month field has a 0 or 1, depending on if the person was enrolled that month.
I'm being asked to generate a table like this:
ID_________ Start_Date End_Date
0000030257 July 1, 2014 Nov 30, 2014
Is there some slam dunk way to do this without a bunch of If/Then statements?
The editor compressed all my space fields, so the column headers are off in some places.
I am working with SP. How can we find out values of parameters when the SP is executed with the default values?
View 9 Replies View RelatedI am trying to remove the dates from a query. my goal is to load it in ssas and add a time dimension. Right now i have to change the dates evrytime i run reports (monthly). Here is the query
drop table #tmptmp
SELECT *, (DATEDIFF(day, enrollmentsDate, ShipmentDate))
- ((DATEDIFF(WEEK, enrollmentsenttDate, InitialShipmentDate) * 2)
+(CASE WHEN DATENAME(DW, enrollmentsentDate) = 'Sunday' THEN 1 ELSE 0 END)
+(CASE WHEN DATENAME(DW, ShipmentDate) = 'Saturday' THEN 1 ELSE 0 END)
[Code] .....
What are the tables are having the Default Constraint those table's Script the User can't generate but remaining tables He/She can generate,If i want DENY he/she to do not generate the script those are not having the DF Constraints what should i do.....
View 1 Replies View RelatedI want to create a check constraint on a table but the constraint values depend upon another table column as well, now one possible way is to create a function to check the column value. But I don’t want to use the function.
Can I do this in a view if so then how can I achieve this.
I have a process to rollover prior quarter data to new quarter in a table.
For example, i have a table with (col1, col2, year, qtr) with data like ( Note: col1 is identity(1,1) )
1,'today',2014,1
2,'tomorrow,2014,1
3,'friday',2014,1
Now when i run my process, above 3 records will be rolled over new quarter 2014 Q2 and the table will be like
1,'today',2014,1
2,'tomorrow,2014,1
3,'friday',2014,1
4,'today',2014,2
5,'tomorrow,2014,2
6,'friday',2014,2
Row 1 with identity 1 has rolled over to new quarter row 4 with identity 4 ( qtr fields are changed )
Row 2 with identity 2 has rolled over to new quarter row 5 with identity 5. Same with last row as well.
Here, i have another table called "ident_map" with columns like (old identity, new identity ) and during rollover i am supposed to load ident_map table with old and new identity. So after rollover is complete, ident_map table should look like
1,4
2,5
3,6
I know using output clause I can capture the new identity values. 4,5,6 in this case. But is there any way to capture both old identity and new identity during rollover so that i can load the ident_map table with old and new identity.
I am trying to setup a constraint on a 2012 database the allows only one "LineitemNumber" for each InvoiceID. I am not certain how to do this. Both of these columns exist in the same table. I know the starting code would look like: ALTER TABLE dbo.InvoiceLineItemBase WITH NOCHECK ADD CONSTRAINT CK_LineItemNumber
View 7 Replies View RelatedI have two tables A(uname,address,full_name) and B(uname,full_name). I want to update table A for all matching case of uname in table B.
View 5 Replies View Related