I'm having an argument with an incumbent self-taught programmer that
it is OK to use null foreign keys in database design.
My take is the whole point of a foreign key is that it's not supposed
to be optional, it's very definition is it's a necessary link to the
parent table and part of the definition. If it's optional it shouldn't
be part of the definition of a table and should be in a linking table
instead.
Hi, I made two tables. The Policy table's rate_limit column references the RateLimit table's id as foreign key. Here is the table definitions.
CREATE TABLE RateLimit ( id INT CONSTRAINT PK_RateLimit_id PRIMARY KEY CLUSTERED, name VARCHAR(20), min INT, max INT );
CREATE TABLE Policy ( id INT CONSTRAINT PK_Policy_id PRIMARY KEY CLUSTERED, rate_limit INT CONSTRAINT FK_Policy_rate_limit FOREIGN KEY(rate_limit) REFERENCES RateLimit(id), min INT, max INT );
Now, I inserted value each table;
INSERT INTO RateLimit VALUES(1,'RateLimit1',1000,10000); INSERT INTO RateLimit VALUES(2,'RateLimit2',2000,20000); INSERT INTO RateLimit VALUES(3,'RateLimit3',3000,30000); INSERT INTO RateLimit VALUES(4,'RateLimit4',4000,40000); INSERT INTO RateLimit VALUES(5,'RateLimit5',5000,50000);
INSERT INTO Policy VALUES(1,1,10,100); INSERT INTO Policy VALUES(2,2,10,100); INSERT INTO Policy VALUES(3,3,10,100); INSERT INTO Policy VALUES(4,4,10,100); INSERT INTO Policy VALUES(5,5,10,100); INSERT INTO Policy VALUES(6,5,10,100); INSERT INTO Policy VALUES(7,4,10,100); INSERT INTO Policy(id,min,max) VALUES(8,10,100);
========================================================================= SELECT A.id,B.name,B.min,B.max FROM Policy A,RateLimit B WHERE A.rate_limit=B.id;
The result of above query statement is like this. --------------------------------------------- id rate_limit min max --------------------------------------------- 1 RateLimit1 1000 10000 2 RateLimit2 2000 20000 3 RateLimit3 3000 30000 4 RateLimit4 4000 40000 5 RateLimit5 5000 50000 6 RateLimit5 5000 50000 7 RateLimit4 4000 40000 ---------------------------------------------
How can I get whole recordset using join, that is, if Policy table's rate_limit is null, return Policy's min/max otherwise, return RateLimit's min/max, just like below result.
I'm using SQL Server 2000. I have an EXTERNAL_FUNDING table and an EXTERNAL_FUNDING_TYPE table. The DDL for the tables is listed below. Each EXTERNAL_FUNDING record has a type field, which is a foreign key to a record in the EXTERNAL_FUNDING_TYPE table. However, I would like for the type to be allowed to be null. When displaying the data, if the type is null, I'd like to show blank text. Here is the query I'm trying to use: SELECT EXTERNAL_FUNDING.id, date_requested as [Request Date],source as [Source/Sponsor],EXTERNAL_FUNDING_TYPE.type AS [Type],amount as [Amount], granted as [Granted] FROM EXTERNAL_FUNDING,EXTERNAL_FUNDING_TYPE WHERE (project_id = @project_id) AND (EXTERNAL_FUNDING.type = EXTERNAL_FUNDING_TYPE.id) ORDER BY date_requested ,source,type
But this query does not return the records with NULL for the type field. Can someone explain to me how I can also return the rows with a NULL type? Thanks!
I have a projects table with 2 foreign key fields that both link to the same employees table because a project has a Package Engineer (PkgEngineerID) and a Contract Administrator (PkgContrAdmin). When I try to insert a record with null values for either or both of these foreign keys I get an error:
The data in row xxx was not commited. The record can't be added or changed. Referential integrity rules require a related record in table 'tblEmployees'. The transaction ended in the trigger. The batch has been aborted.
An insert statement for the above would look something like the following:
I have two tables 1) tblCustomer (ID, Name, City) 2) tblemp (ID, NAME, Dept.ID, tblcustomer.ID) Both the tables have ID as PKA emp can be either assigned a) All customers b)single customer c) NO customer Pls note:- there will never be 2 or 3 customer linked to emp (my actuall requirement tables are different but to explain i am using the above tables) I know how to assign single customer......but had problem how to link all customers and "no customer" Please tell me if the following solution is right?1) I will manually insert a record in tblCustomer with id 0 as " all customers" and will not allow the user to delete it 2) store null in FK if it is "no customer" Also please tell me is it ok to store one more value in tblCustomer as -1 and take it as "No customer" I have a DDL in the Employee page which should be displaying the names of allthe customers with 2 extra values "ALL CUSTOMERS" and "SELECT" Select is the default value in DDL which says "NO CUSTOMER" selected yet Thank youSara
I have a table called Appointment, for storing (you guessed it) appointments at a medical practice. If an appointment is cancelled, I want to collect a cancellation reason, so let's say that I create a second table called Cancellation which has a foreign key relating to the Appointment table's primary key, AppointmentID, and another column, Reason. Now, in order to indicate that an appointment was cancelled, I could include a Cancelled column in the Appointment table with a bit datatype, or instead I could infer that an appointment must be cancelled if it has a corresponding record in the Cancellation table.
It may be that it'd be better to store the cancellation reason in the Appointment table - But regardless, let's say I stick with the two-table solution described above, and I subsequently want to write a query to list all appointments which have been cancelled. If I had the Cancelled column in the Appointment table, I could simply query for all records in that table where that column's value was FALSE. If I went the other way and DIDN'T have a Cancelled column, I could instead write a query joining the Appointment and Cancellation tables to return all records in Appointment with a corresponding record in Cancellation.
That latter method, whilst slightly more complicated because it involves joining two tables, seems to me to be the most normalised. Instead of storing the fact that an appointment is cancelled in two different tables, that fact is only stored in the Cancellation table. Would there be a performance hit in using the two-table, 'inferred cancellation' method rather than just having a bit column in the Appointment table? Would that performance hit be enough to persuade you to use a Cancellation column in the Appointment table instead? And what about if I were to apply that method to other things associated with each appointment, e.g. Is it completed? Is it chargeable to the client or an insurance company? Is the client and in-patient or out-patient?
I know this is probably a flick of a switch but I cannot figure out which switch. Setup is SQL Server / Stored Procedures / DAL / BLL(skipped for testing) / PL. The stored procedure queries from only one table and two columns are ignored because they are being phased out. I can run the stored procedure and preview the data in the DAL but when I create a page with an ODS linked to the DAL and a GridView I get this error. I checked every column that does not allow nulls and they all have values. I checked unique columns (ID is the only unique and is Identity=Yes in the table definition). I checked foreign-key columns for values that are not in the foreign table and there are none. Any ideas why do I get this? Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Hi, I am getting the above error when trying to load a report into my Web Application, I have tracked the error down to one specific field in my database. Even though this field is a NVarChar field and is of size 30 it would seem that there is an issue returning the value from the field. I can write it into the database no problems but when I try to get it out of the database it returns the above error. e.g MOB 401.908.804 - Fails 0401.907.324 - okay 8239 9082 (pager) - fails Anyone got an idea on how to fix this???? Regards.. Peter.
Hey. I need to substitute a value from a table if the input var is null. This is fine if the value coming from table is not null. But, it the table value is also null, it doesn't work. The problem I'm getting is in the isnull line which is in Dark green color because @inFileVersion is set to null explicitly and when the isnull function evaluates, value returned from DR.FileVersion is also null which is correct. I want the null=null to return true which is why i set ansi_nulls off. But it doesn't return anything. And the select statement should return something but in my case it returns null. If I comment the isnull statements in the where clause, everything works fine. Please tell me what am I doing wrong. Is it possible to do this without setting the ansi_nulls to off??? Thank you
set ansi_nulls off
go
declare
@inFileName VARCHAR (100),
@inFileSize INT,
@Id int,
@inlanguageid INT,
@inFileVersion VARCHAR (100),
@ExeState int
set @inFileName = 'A0006337.EXE'
set @inFileSize = 28796
set @Id= 1
set @inlanguageid =null
set @inFileVersion =NULL
set @ExeState =0
select Dr.StateID from table1 dR
where
DR.[FileName] = @inFileName
AND DR.FileSize =@inFileSize
AND DR.FileVersion = isnull(@inFileVersion,DR.FileVersion)
In my report i have CNAME parameter , which allows null value. I checked Allow null value check box in report parameter properties.
when i preview the report , it displays checked NULL check box beside CNAME parameter . I want to give some meaningful name(i.e.ALLCustomers) to this checkbox instead of NULL.
In the flat file SampleID and Product are populated in the first row only, rest of the rows only have values for Rep_Number, Protein, Fat, Solids.
SampleID and Product are blank for the rest of the rows. So my task is to fill those blank rows with the first row that has the sampleID and Product and load into the table.
I have a report that is run on a monthly basis with a default date of null. The stored procedure determines the month-end date that it should use should it be sent a null date.
The report works fine when I tell it to create a history entry; however, when I try to add a subscription it doesn't appear to like the null parameter value. Since I have told the report to have a default value of null it doesn't allow me to enter a value on the subscription page.
Now, I suppose I could remove the parameter altogether from the stored proc, but then the users would never be able to run the report for a previous time period. Can someone explain to me why default values aren't allowed to be used on subscriptions when they seem to work fine for ad hoc and scheduled reports? This is really quite frustrating as most of my reports require a date value and default to null so that the user doesn't have to enter them for the latest data.
An internal error occurred on the report server. See the error log for more details. (rsInternalError) Get Online Help
I run a stored procedure for which I have a return variable. The stored procedure returns the ID of a row in a table if it exists:
m_sqlCmd.ExecuteScalar();
The m_sqlCmd has been fed an SQLParameter with direction set to output. When the stored proc returns, I want to test it. Now when there IS a row it returns the ID ok. When the row doesn't exist, in my watch I have:
m_sqlParam.SqlValue with value {Null}
I can't seem to work out how to test this value out. I've tried several things but none seem to work.
This line compiles ok, but the following runs into the IF statement as if the SqlValue is null??
if (m_sqlParam.SqlValue != null).... {
// I'm here!! I thought the watch says this is null??? }
Sorry if this is obvious, but I can't work this one out!!
Looks like there was a fix and then I read this fix is not a fix. Does anyone know how this can be rectified? Does it mean that only Windows authentiation is the only way it works. The Software is over 2 years old, there are no excuses.
I am getting this error: "Cannot insert the value NULL into column 'OrderID', table 'outman.outman.Contact'; column does not allow nulls. INSERT fails." -- But my value is not null. I did a response.write on it and it show the value. Of course, it would be nice if I could do a breakpoint but that doesn't seem to be working. I'll attach a couple of images below of my code, the error, and the breakpoint error.
Server Error in '/' Application.
Cannot insert the value NULL into column 'OrderID', table 'outman.outman.Contact'; column does not allow nulls. INSERT fails. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'OrderID', table 'outman.outman.Contact'; column does not allow nulls. INSERT fails.Source Error:
Line 89: sContact.Phone = sPhone.Text.Trim Line 90: sContact.Email = sEmail.Text.Trim Line 91: sContact.Save() Line 92: Line 93: Dim bContact As Contact = New Contact()Source File: F:InetpubwwwrootOutman KnifeCheckout.aspx.vb Line: 91 Stack Trace:
hi,my structure table in database:Amount float(53) not null default 0when i try to run his script:alter table ABC alter column Amount float(53) nullit can only set the Amount to allow null, but can't set the defaultvalue to empty.anyone know how to set the field to allow null and default set toempty, no value.thanks
I've built a sample CLR function with the following declaration....
CREATE FUNCTION GetManager(@DeptCode nvarchar(3)) RETURNS nvarchar(1000) WITH RETURNS NULL ON NULL INPUT AS EXTERNAL NAME Assembly1.[ClassLibrary1.MyVBClass].MyManager
It returns the value "Unknown" as it would have for any unknown DeptCode, as-programmed.
I'm of the theory it should have returned NULL without actually firing the function? Or is this only for non-CLR items... or stored procedures, not functions?
We have a case where in we should show date based on conditions for e.g if we had a column defined as
col varchar(10) then we would show col as 'NULL' for some condition and actual value when no condition
Normaly date values are stored here e.g under col 20150901 .
Case when col>'20150901' then 'NULL' else col end as Derivedcol
Note this is an extract process and we are presenting data by pumping the data in a table .
Now there is another similar column -colz varchar(10) which stores date but doesnt have case condition so whenever date has no value its shows null which is database null.
So whats the difference between database null and string null ?
How can we show database null for the case condition instead of string "null"?
I have two columns A (which allows nulls) and B( which does not allow nulls). How can I add the contents of columns A and B SO THAT I DO NOT GET A NULL RESULT WHEN A IS NULL.
The result of A+B concatanation will be stored in a column, C.
I've got a query on a particular table returning an odd result:
SELECT DISTINCT WorkStation FROM Invoice WHERE WorkStation Is Not Null ORDER BY WorkStation
This query returns the rows I'd expect plus a null row. This doesn't happen in databases at other sites, or in other tables at this site. The following query behaves as I'd expect returning only non-null AccountNumbers.
SELECT DISTINCT AccountNumber FROM Suppliers WHERE AccountNumber Is Not Null ORDER BY AccountNumber
I can't reproduce these results on another site on a table of the same structure, or on another table at this site.
Any suggestions as to what might be going on?
Pertinent info: --- select @@Version
Microsoft SQL Server 2000 - 8.00.760 (Intel X86) Dec 17 2002 14:22:05 Copyright (c) 1988-2003 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 1) --- dbcc checkdb Abridged result: CHECKDB found 0 allocation errors and 0 consistency errors in database 'POS'. --- SELECT * INTO #Inv FROM Invoice
SELECT DISTINCT WorkStation FROM #Inv WHERE WorkStation Is Not Null ORDER BY WorkStation
Does not reproduce this problem (and so is a probable fix) but the questions remains, what causes this?
I have 595 default constraints in my database. I can return a list of them using the following:
select * from sys.default_constraints
Is there a way I can return a list of just the ones where NULL is still allowed? I want to update all of the columns with a default value to not allow NULLs.
I've NEVER EVER had this issue, I have always done this and it works great both locally and remotely.
I have a table, which is a "customers" table.
I have a stored procedure which takes in parameters (name, address, password etc...) and returns me back, via a parameter declared as output - the customer ID.
I've always done this, and works great.
Now, this works fine locally.
IF I try to run this/do the exact same execution of commands (create a customer) remotely (where the database is stored, so copying everything from local to "over there") it does not work.
I get a DBNULL value back from the parameter, declared as an int output.
IF I copy and paste this Stored procedure Query/command into Query Analyzer and execute it (on the remote connection) and run it, giving it the exact same values as I do, it works perfect and returns me the correct value.
I've even dropped and recreated the stored procedure but makes no difference.
Any ideas why?
here is the proc....
CREATE PROCEDURE [dbo].[DoCreateNewCustomer] ( @theFirstName nvarchar(25), @theLastName nvarchar(25), @theAddress nvarchar(50), @theCity nvarchar(15), @thePostCode nvarchar(9), @thePhoneNumber nvarchar(21), @theMobilePhoneNumber nvarchar(21), @theIPAddress nvarchar(25), @thePassword nvarchar(50), @theEmailAddress nvarchar(30), @result int output ) AS SET @result = (SELECT [ID] FROM Customers WHERE emailAddress = @theEmailAddress) IF @result IS NOT NULL SET @result = -1 ELSE BEGIN SET @result = @@IDENTITY INSERT INTO Customers (
Firstname, Lastname, Address, City, Postcode, PhoneNumber, MobileNumber, IPAddress, [Password], EmailAddress
Any ideas why it does not work when calling the stored proc from either a web app, or through QA remotely but works fine when I run that command in QA or locally?
Again, if I do:
EXEC DoCreateNewCustomer { params } - the output result it gives me is DBNULL (if on remote connection)
If I do this locally, perfect
If I copy and paste pretty much the SP into QA and execute it on the remote connection, works great, and also locally.
I have a pivot transform that pivots a batch type. After the pivot, each batch type has its own row with null values for the other batch types that were pivoted. I want to group two fields and max() the remaining batch types so that the multiple rows are displayed on one row. I tried using the aggregate transform, but since the batch type field is a string, the max() function fails in the package. Is there another transform or can I use the aggragate transform another way so that the max() will work on a string?
Hello everyone,I have a table that stores data of a Person. For personal data, there are 2 different fields, for example... a personal address and a professional address, a peronal email and a professional email, a personal phone num and a professional phone num, etc...My question is, i would like to know if it's possible to make it for at least one of these fields to be NOT NULL, but not necessarily both.I'll have 2 fields: emailPersonalemailProfessional Can i make it so that, when inserting or updating data, sql checks to see if AT LEAST ONE of the emails is filled in (both can also be filled in)... I dont care which one is filled in, as long as ONE is filled in... Thanks in advance,SuperJB
Hello all I am trying to run a sql statement, (without having to run stored procedures), that will lookup a value stored in a Record.field., otherwise ignore the value if it is blank. I have a field tied to a Microsoft Access form - ItemLocation. If the user selects a unique ItemLocation the report will attempt to locate all values within that ItemLocation. If the user decides to leave the field blank, I would like for it to return all values for every ItemLocation. If anyone can help, I would really appreciate it. I will attach code. My problem is the last line of this SQL statement. If F.ITemLocation is null, I get no data. I would like for it to return everything. Thank you.
Code: SELECT DISTINCT B.BarCodeID, A.ItemDescription, A.ItemCategory, A.TypeOfItem, A.SerialNumber, B.ItemLocation, B.LocationID, B.LastUpdate, B.TrackItID, B.UserID FROM tblMISFixedAssetTable A, tblMISFixedAssetTable2 B WHERE A.BarCodeID = B.BarCodeID AND A.DisposalDate is null AND B.LastUpdate = (Select Max(C.LastUpdate) from tblMISFixedAssetTable2 C Where B.BarCodeID = C.BarCodeID) AND B.BarCodeID in (Select D.BarCodeID from tblMISFixedAssetTable3 D Where D.FiscalYear = (Select E.FiscalYear from tblReportFY E)) AND B.ItemLocation = (Select F.ItemLocation from tblReportFY F)
Is there any way in SQL Server 6.5 to change a column that was originally set up as nullable to not accept nulls? None of the values in this column contain null values. I need to add a primary key constraint on the column for replication purposes and SQL won't let me because the column is nullable.