Insert NULL Values To Foreign Key Fields

Jan 15, 2008

Hi all,

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:

INSERT INTO tblPackages (PkgNo, PkgName, PkgEngineerID, PkgContrAdmin, PkgRemark)VALUES (1234, 'My Package', NULL, NULL, 'My Package remark')

And the create table statements are:

USE [PASSQL]GO/****** Object: Table [dbo].[tblPackages] Script Date: 01/15/2008 23:25:26 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[tblPackages]( [ID] [int] IDENTITY(1,1) NOT NULL, [PkgNo] [nvarchar](20) NULL, [PkgName] [nvarchar](255) NULL, [PkgEngineerID] [int] NULL, [PkgContrAdmin] [int] NULL, [PkgRemark] [nvarchar](255) NULL, [upsize_ts] [timestamp] NULL, CONSTRAINT [aaaaatblPackages_PK] PRIMARY KEY NONCLUSTERED ( [ID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOALTER TABLE [dbo].[tblPackages] WITH NOCHECK ADD CONSTRAINT [FK_tblPackages_tblEmployees] FOREIGN KEY([PkgEngineerID])REFERENCES [dbo].[tblEmployees] ([ID])GOALTER TABLE [dbo].[tblPackages] CHECK CONSTRAINT [FK_tblPackages_tblEmployees]GOALTER TABLE [dbo].[tblPackages] WITH NOCHECK ADD CONSTRAINT [FK_tblPackages_tblEmployees1] FOREIGN KEY([PkgContrAdmin])REFERENCES [dbo].[tblEmployees] ([ID])GOALTER TABLE [dbo].[tblPackages] CHECK CONSTRAINT [FK_tblPackages_tblEmployees1]

And:

USE [PASSQL]GO/****** Object: Table [dbo].[tblEmployees] Script Date: 01/15/2008 23:28:01 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[tblEmployees]( [ID] [int] IDENTITY(1,1) NOT NULL, [EmpName] [nvarchar](255) NULL, [EmpShort] [nvarchar](255) NULL, [upsize_ts] [timestamp] NULL, CONSTRAINT [aaaaatblEmployees_PK] PRIMARY KEY NONCLUSTERED ( [ID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]
Any ideas on how to accomplish this would be great!
Thanks in advance!

View 4 Replies


ADVERTISEMENT

1) Null Value In Foreign Key 2) Extra Value To Indicate All The Values In PK Table Apply

Feb 27, 2007

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

View 10 Replies View Related

Null Values In Calculated Fields

May 22, 2008



Hi all

I have a calculated fields in report designer such as a + b + c + d. In sql server if I run this query

select a + b + c + d from table1

and any of a,b,c or d is null, the result is null.

whereas in calculated fields, it does not return null but infact ignores the null value and treats it as zero.

I want my calculated field to be null if any of the values are null.
Is it possible? I cannot use the isNothing function because I have too many fields and it will be quite cumbersome.

Thanks

View 4 Replies View Related

Concatenating Fields With NULL Values

Jul 11, 2006

Hey everyone,

This is probably a very simple question, but I am just stumped. I am storing different name parts in different fields, but I need to create a view that will pull all of those fields together for reports, dropdowns, etc.

Here is my current SELECT statement:

SELECT m.FName + SPACE(1) + m.MName + SPACE(1) + m.LName + ', ' + m.Credentials AS Name,
m.JobTitle,
m.Company,
m.Department,
m.Address,
m.City + ', ' + m.State + ' ' + m.Zipcode AS CSZ,
m.WorkPhone,
m.FAX,
m.Email,
c.Chapter,
m.Active,
s.Sector,
i.Industry
FROM tblMembers m
LEFT OUTER JOIN tblChapters c
ON m.ChapterID = c.ChapterID
LEFT OUTER JOIN tblSectors s
ON m.SectorID = s.SectorID
LEFT OUTER JOIN tblIndustries i
ON m.IndustryID = i.IndustryID
WHERE m.DRGInclude = 1

My problem is that I don't know how to test for NULL values in a field. When you concatenate fields that contain NULL values, the entire contactenated field returns NULL. I am not aware of an IF statement that is available within the SELECT statement.

The first thing I would like to accomplish is to test to see if MName contains NULL. If it does I do not want to include + SPACE(1) + m.MName in the clause. Then, if Credentials contains NULL I do not want to include + ', ' + m.Credentials in the clause.

Can someone tell me what I am missing? Is there a function that I can use for this?

Thanks,

View 8 Replies View Related

Null Values In Datetime Fields, Howto?

Jul 12, 1999

Hi,
When I try to insert a new record into a table that has a datetime field that allows nulls, a default 01/01/1900 date is inserted instead of null. I recreated the table and set the datatype to smalldatetime and I still get the error. What have I missed?

View 1 Replies View Related

Inserting NULL Values On Date Fields Trhough DAL

Jul 25, 2006

I am using a DAL and i want to insert a new row where one of the columns is DATE and it can be 'NULL'.
I am assigning SqlTypes.SqlDateTime.Null.
But when the date is saved in the database, i get the minvalue (1/01/1900) . Is there a way to put the NULL value in the database using DAL????how can i put an empty date in the database?
THANK YOU!!!

View 3 Replies View Related

Efficiency In Inserting Null Values Into Fields Which Allow Nulls.

Aug 9, 2004

Hi,
I have fields in my table which allow nulls. Is it efficient to not insert anything (the field automatically shows up as null in this case) and leave or store some value into it. The field is a smallint field?

Thanks

View 2 Replies View Related

Insert Values In Multiple Table With Foreign Key

Feb 28, 2008

Hi,

I've been working as web dev for quite sometime now but there are still few things that i would like to clarify. Hope you guys can shed lights.

I currently have several tables and all this tables are having some 1 to many relationships. I know that how i insert value into my tables are very inefficient. I do it in this manner..
-> Insert a value in TableA
-> Query the latest ID that i have inserted in Table A then
-> Insert this value in TableB. And so on and so forth.

I believe there is an efficient way to to do this but i'm not sure how? Could anyone shed me a light on this matter?

Your reply would be highly appreciated. TIA.

View 6 Replies View Related

SSIS Import Of CSV Don't Recognize NULL Values For VARCHAR Fields

Sep 4, 2007

Hi, i'm new to SSIS and trying to import some csv files (comma delimited) into SQL Server. A NULL value for a CHAR column is correctly regonized as NULl in SQL Server, but a NULL value for of a mapping to a VARCHAR column in SQL Server is not recognized correctly and i get the value "'NULL'" in SQL Server (including the single comma.

Sample:

CSV file contains columns A and B. A and B contains the Text NULL.
Column A is mapped to a CHAR field, and column B is mapped to a VARCHAR field in SQL Server.
After the import, SQL has the following value: A = NULL as NULL, B 'NULL' as text.

did anyone else had this problem?

thanks so much for any help.

View 4 Replies View Related

Need Help With Insert Statement On Table With Several Non-null Fields

Apr 30, 2007

On my aspx page I have a basic sqldatasource and gridview - both were set up using the wizards. The SQL Server 2000 database table that the sqldatasource is querying has some fields in it that are set to not allow nulls, however, the gridview control is not displaying all of the fields in the table - including some of the non-null fields.
My problem is, when I run an insert on the table from my aspx page, I get an error that says: "Cannot insert the value NULL into column 'ColumnName', table 'TableName'; column does not allow nulls. INSERT fails. The statement has been terminated."
The 'ColumnName', as you may have guessed, is one of the aforementioned columns that doesn't allow nulls, but isn't in the GridView.
How can I do an insert on this table without messing with the non-null fields. Those fields are relevant to the purposes of the gridview, so I don't want to display them, let alone allow editing of them.
Any suggestions on my options would be greatly appreciated!
Thanks
Capella07

View 2 Replies View Related

Insert Values Of All The Fields Into Variable?

Aug 7, 2014

I need to create a stored procedures, this procedure will receive two parameters:

@TableName

@KeyField

I need to storage into a variable the values of ALL THE FIELDS separeted by |

For example if my table is Customers

CustomerID CustomerName City

111 Adventure Boston

222 Pubs NY

And I execute EXEC mysp 'Customers',111

I need a return value like this

@ReturnValue = 111|Adventure|Boston

I create something like this

CREATE PROCEDURE my sp
@table varchar
@key numeric
AS
@field varchar(40),
@object int
Select @object = object_id from systables where name =@table

--The instructions to create a cursor

WHILE (@@FETCH_STATUS = 0 )
Select @object = name from sys.columns where object_id = @object

--The instructions to close and deallocate the cursor

I have alredy to save the value using the EXEC command but is not working; something like

@String = Select @object from @table where CustomerID = @keyValue

View 1 Replies View Related

UGH! Failed To Enable Constraints. One Or More Rows Contain Values Violating Non-null, Unique, Or Foreign-key Constraints.

Jan 9, 2007

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.

View 3 Replies View Related

Failed To Enable Constraints. One Or More Rows Contain Values Violating Non-null, Unique, Or Foreign-key Constraints.

Jan 17, 2008

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.

View 7 Replies View Related

Insert Null Values

Jan 28, 2005

Hi all

Iam having some problems with null values

try
{
cmd.Parameters["@fmv"].Value = Convert.ToDecimal(TextBox13.Text);
}
catch
{
cmd.Parameters["@fmv"].Value =System.Data.SqlTypes.SqlDecimal.Null;
}

for Empty Textbox values
i am getting the following error,

System.Data.SqlTypes.SqlNullValueException: Data is Null. This method or property cannot be called on Null values.

My Database is allowed to accept null values.

System.Data.SqlType.SqlDatetime.Null works but SqlDecimal.Null does not work.

Could any one help me with this?

Thanks

Raj

View 2 Replies View Related

Aspnet_regsql.exe - Cannot Insert Null Values

Oct 20, 2006

Im trying to setup a SQL server 2000 database to use membership & roles.  Running aspnet_regsql.exe gives me the following errorsSetup failed.Exception:An error occurred during the execution of the SQL file 'InstallCommon.sql'. The SQL error number is 515 and the SqlException message is: Cannot insert the value NULL into column 'Column', table 'tempdb.dbo.#aspnet_Permissions_________________________________________________________________________________________________000000008000'; column does not allow nulls. INSERT fails.Warning: Null value is eliminated by an aggregate or other SET operation.The statement has been terminated.----------------------------------------Details of failure----------------------------------------SQL Server: Database: [AddressVerification]SQL file loaded:InstallCommon.sqlCommands failed:CREATE TABLE #aspnet_Permissions(    Owner     sysname,    Object    sysname,    Grantee   sysname,    Grantor   sysname,    ProtectType char(10),    [Action]    varchar(20),    [Column]    sysname)INSERT INTO #aspnet_PermissionsEXEC sp_helprotectIF (EXISTS (SELECT name              FROM sysobjects             WHERE (name = N'aspnet_Setup_RestorePermissions')               AND (type = 'P')))DROP PROCEDURE [dbo].aspnet_Setup_RestorePermissionsSQL Exception:System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Column', table 'tempdb.dbo.#aspnet_Permissions_________________________________________________________________________________________________000000008000'; column does not allow nulls. INSERT fails.Warning: Null value is eliminated by an aggregate or other SET operation.The statement has been terminated.   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async)   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()   at System.Web.Management.SqlServices.ExecuteFile(String file, String server, String database, String dbFileName, SqlConnection connection, Boolean sessionState, Boolean isInstall, SessionStateType sessionStatetype)Ive run this many times on other servers and have never come across this problem before.  Has anyone else ?  Does anyone know the cause and if there is a fix ??** I am logged in with full admin privaliges tiaMark. 

View 3 Replies View Related

Insert Command Does Not Like Null Values.

Jan 5, 2004

- I'm a Novice -

I'd like to use an insert command to insert whatever data that is on the unbound form. The first three fields are required and I check those values prior to executing the code below. But some fields may be null.

Dim strSQL as string
.
.
code
.
.
strSQL = "INSERT INTO tblCase " & _
"(Case_SiteName, " & _
"Case_PatientSequenceNumber, " & _
"Case_PatientInitials, " & _
"Case_DOB, " & _
"Case_ProcedureDate, " & _
"Case_Investigator, " & _
"Case_Institution, " & _
"Case_Value) " & _
"VALUES ('" & Me.cboSiteName & "', " & _
Me.txtPatientNumber & ", '" & _
Me.tbxPatientInitials & "', '" & _
Me.tbxPatientDOB & "', '" & _
Me.tbxProcDate & "', '" & _
Me.tbxInvestigator & "', '" & _
Me.tbxInstitution & "', " & _
Me.grpValue & ");"

CurrentProject.Connection.Execute strSQL

But, when any of the last four are unanswered, i get an error. Any, or all of the last four can be blank. Any suggestions?

View 14 Replies View Related

How Do I Insert A Record With Possible NULL Values Using A Tableadapter.

Feb 26, 2008

I'm sorry, this question has a pretty long preamble, but bear with me as this will fully explain my problem, and save a number of clarification questions.I am using Visual Web Developer 2005 Express, with SQL Server 2005. After reading a Microsoft article saying that it was much better to use a three tier architecture with data adapters than to write explicit queries, I have used this approach extensively, and generally it works very well.  Typical code patterns are: -        Dim taPassenger As New ShippingTableAdapters.VPassengerTableAdapter        Dim tbpassenger As Shipping.VPassengerDataTable        Dim trpassenger As Shipping.VPassengerRow        .....        '   to process all passengers from a voyage: -        tbpassenger = taPassenger.GetDataByVOYid(Voyageid)        For Nbr As Integer = 1 To tbpassenger.Count            trpassenger = tbpassenger(Nbr - 1)             '    I now have the row available in properly-typed fields, eg trpassenger.vpxName             ...        Next        '   to read and process a single passenger        tbpassenger = tapassenger.GetDataByVPXid(VPXid)        trpassenger = tbpassenger(0)The table adapter has been created with Insert,Update, Delete methods.   Thus you can assign values to row fields, and then update the row: -        trpassenger.VPXName = "New Name"        ....        tapassenger.update(trpassenger)There are actually several overloads of the update method:  you could have written a field list, like this, where the names (VPXid etc) would be defined in my program as variables of the appropriate type for the corresponding column.        tapassenger.update(VPXid, VPXName, VPXAge, ....HOWEVER,  this doesn't work properly if you have non-string data that could be null.   Thus if the fourth field is a foreign key that could be null, if you write        Dim VPXVoyId as Nullable(of GUID)        VPXVoyid = nothing        tapassenger.update(VPXid, VPXname, VPXAge, VPXVoyid, ...or         Trpassenger.VPXVoyid = Nothing        tapassenger.update(trpassenger) you do NOT put a null value into the database.  Instead you store a value of "00000000-0000-0000-0000-000000000000".   You can solve this annoying problem in two ways: -A.   If you will ALWAYS be storing a null value at this point of your program, then simply write the update statement like this: -        tapassenger.update(VPXid, VPXname, VPXAge, Nothing, ...Here "Nothing" actually means "DBNull" even though it doesn't mean this when used in a normal VB assignment (and neither does DBNull).B   You can use the SetxxxxNULL method: -        If trpassenger.VPXVoyid = nothing then             trpassenger.SetVPXVoyidNull        End If        tapassenger.update(trpassenger) Thus when the program logic is complex and there are many paths to the update statement I will often put statements such as this in front of the update statement, using SetxxxxxNull for all non-string values that may be null.  You don't need to worry about string values because the Nullvalue property can be used to simply say that Null values are empty, and it all works properly, but for reasons unknown Microsoft have prohibited this for other data types. Now at last we get to my question, which is "How do I do the equivalent for an Insert?"   tapassenger.insert does not have any overloads, and the only form is  tapassenger.insert(field list).   But this creates the problem above:  if VPXVoyid = nothing then I insert the not-null value of "00000000-0000-0000-0000-000000000000".   If I COULD use the form tapassenger.insert(trpassenger), then I'd have another problem: if you haven't set trpassenger (for example with trpassenger = tbpassenger(0)) then it will not exist, so you will get an exception when you try to reference it.  Yet you can't write    If isnothing(trpassenger) then       trpassenger = new shipping.vpassengerrow)         (I've tries this both as an assignment, and as a Dim statement)    end ifSo far I can think of only two solutions, both awful: -a/    Use multi-choice logic to choose an appropriate insert statement.  If there is only one or two possibly-null fields, I could write:-        If field4 = nothing then            trpassenger.insert (VPXid, VPXname, VPXAge, Nothing, ..        However if there is more than one possibly-null field, you need (2 to the power of  nbr-of-possibly-null-fields) insert statements, with of course a lot of testing to choose which oneb/    I could insert the record with nulls, then read it back and update it.  Surely there is a better way!   Help! Thank you, Robert Barnes.    

View 2 Replies View Related

How To Insert Null Values Into A DataBase Field

May 9, 2005

I have a function that updates a table in sql server
If a field is left blank I want the database field set to Null. I use:sqlCmd.Parameter.Add("@somefield, someintvalue) to pass all my values to the database.
if someintvalue is null I want to set @somefield to dbnull
How can I do this? I get errors if I submit a null integer when there is a foreign key constraint. What is the best way to handle this? should I just make all parameters objects? so that I can set them to DBNull.Value?
Also on a side note, when you are populating fields from a datatable, is there a better way to set the values (i.e. of a textbox) than cheking for DBNull before assigning?

View 2 Replies View Related

How To Insert NULL Char Values In SQLSERVER With A SQL Sentence?

Jul 20, 2005

Hi everyone!I am working with Delphi v7 and MS SQLServer.I am trying to insert data in a table with a SQL sentence. Some of thefields of my table are type char or varchar, and they can have nullvalues.¿What do i have to write in the SQL sentence to insert a null value inthose fields?I tried with '', an empty String, but it doesnt work, the tablesstores an empty String (logical :-)).In the SQLServer GUI you have to press CTRL + 0 to insert a NULLvalue, but how can i tell this to the SQLServer through a SQLSentence?Well, thank you very much.

View 2 Replies View Related

Compressing Multiple Rows With Null Values To One Row With Out Null Values After A Pivot Transform

Jan 25, 2008

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?

-- Ryan

View 7 Replies View Related

Can't Create A Foreign Key Using Non_primary Key Fields

Aug 9, 2004

Howdy all !
I'm just a bit on the frustrated side cause I want to create a foreign key but SQL Server won't let me. :(

I have table A with a primary key of main_id
I have table B with a primary key of another_id

Table A has a corresponding field called another_id.

I'm trying to create a foreign key between Table A & Table B on another_id but since it's not the Primary Key in Table A I get the following error:

There are no primary or candidate keys in the referenced table 'A' that match the referencing column list in the foreign key 'fk_classB_classA'.

Am I missing something totally obvious here? Why should I have to create a foreign key on a primary key?

What I find interesting is that I can create the relationship from enterprise manager but when I script it out is when I run into problems.

Here's the script I'm using:

Begin Code

alter table B add
constraint fk_classB_classA foreign key
(classB) references A (classB)
on delete no action
on update no action

End Code

Any help is greatly appreciated.

tam

View 6 Replies View Related

Derived Fields/foreign Keys

Feb 16, 2006

firstly, how do u write a derived field in sql table, e.g you are following a logical design and you are calculating a score for a match table.

secondly, if a foreign key is being used as a primary key in another table, do u have to set it to NOT NULL ?

View 1 Replies View Related

Null Foreign Key

Jul 20, 2005

I'm having an argument with an incumbent self-taught programmer thatit 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 supposedto be optional, it's very definition is it's a necessary link to theparent table and part of the definition. If it's optional it shouldn'tbe part of the definition of a table and should be in a linking tableinstead.Comments?

View 10 Replies View Related

Using Foreign Key Has Null Value...

Oct 4, 2007

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.

---------------------------------------------
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
8 10 100
---------------------------------------------

View 3 Replies View Related

Cannot INSERT Data To 3 Tables Linked With Relationship (INSERT Statement Conflicted With The FOREIGN KEY Constraint Error)

Apr 9, 2007

Hello
 I have a problem with setting relations properly when inserting data using adonet. Already have searched for a solutions, still not finding a mistake...
Here's the sql management studio diagram :

 and here goes the  code1 DataSet ds = new DataSet();
2
3 SqlDataAdapter myCommand1 = new SqlDataAdapter("select * from SurveyTemplate", myConnection);
4 SqlCommandBuilder cb = new SqlCommandBuilder(myCommand1);
5 myCommand1.FillSchema(ds, SchemaType.Source);
6 DataTable pTable = ds.Tables["Table"];
7 pTable.TableName = "SurveyTemplate";
8 myCommand1.InsertCommand = cb.GetInsertCommand();
9 myCommand1.InsertCommand.Connection = myConnection;
10
11 SqlDataAdapter myCommand2 = new SqlDataAdapter("select * from Question", myConnection);
12 cb = new SqlCommandBuilder(myCommand2);
13 myCommand2.FillSchema(ds, SchemaType.Source);
14 pTable = ds.Tables["Table"];
15 pTable.TableName = "Question";
16 myCommand2.InsertCommand = cb.GetInsertCommand();
17 myCommand2.InsertCommand.Connection = myConnection;
18
19 SqlDataAdapter myCommand3 = new SqlDataAdapter("select * from Possible_Answer", myConnection);
20 cb = new SqlCommandBuilder(myCommand3);
21 myCommand3.FillSchema(ds, SchemaType.Source);
22 pTable = ds.Tables["Table"];
23 pTable.TableName = "Possible_Answer";
24 myCommand3.InsertCommand = cb.GetInsertCommand();
25 myCommand3.InsertCommand.Connection = myConnection;
26
27 ds.Relations.Add(new DataRelation("FK_Question_SurveyTemplate", ds.Tables["SurveyTemplate"].Columns["id"], ds.Tables["Question"].Columns["surveyTemplateID"]));
28 ds.Relations.Add(new DataRelation("FK_Possible_Answer_Question", ds.Tables["Question"].Columns["id"], ds.Tables["Possible_Answer"].Columns["questionID"]));
29
30 DataRow dr = ds.Tables["SurveyTemplate"].NewRow();
31 dr["name"] = o[0];
32 dr["description"] = o[1];
33 dr["active"] = 1;
34 ds.Tables["SurveyTemplate"].Rows.Add(dr);
35
36 DataRow dr1 = ds.Tables["Question"].NewRow();
37 dr1["questionIndex"] = 1;
38 dr1["questionContent"] = "q1";
39 dr1.SetParentRow(dr);
40 ds.Tables["Question"].Rows.Add(dr1);
41
42 DataRow dr2 = ds.Tables["Possible_Answer"].NewRow();
43 dr2["answerIndex"] = 1;
44 dr2["answerContent"] = "a11";
45 dr2.SetParentRow(dr1);
46 ds.Tables["Possible_Answer"].Rows.Add(dr2);
47
48 dr1 = ds.Tables["Question"].NewRow();
49 dr1["questionIndex"] = 2;
50 dr1["questionContent"] = "q2";
51 dr1.SetParentRow(dr);
52 ds.Tables["Question"].Rows.Add(dr1);
53
54 dr2 = ds.Tables["Possible_Answer"].NewRow();
55 dr2["answerIndex"] = 1;
56 dr2["answerContent"] = "a21";
57 dr2.SetParentRow(dr1);
58 ds.Tables["Possible_Answer"].Rows.Add(dr2);
59
60 dr2 = ds.Tables["Possible_Answer"].NewRow();
61 dr2["answerIndex"] = 2;
62 dr2["answerContent"] = "a22";
63 dr2.SetParentRow(dr1);
64 ds.Tables["Possible_Answer"].Rows.Add(dr2);
65
66 myCommand1.Update(ds,"SurveyTemplate");
67 myCommand2.Update(ds, "Question");
68 myCommand3.Update(ds, "Possible_Answer");
69 ds.AcceptChanges();
70

and that causes (at line 67):"The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_Question_SurveyTemplate". The conflict occurred in database
"ankietyzacja", table "dbo.SurveyTemplate", column
'id'.
The statement has been terminated.
at System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.Update(DataSet dataSet, String srcTable)
at AnkietyzacjaWebService.Service1.createSurveyTemplate(Object[] o) in J:\PL\PAI\AnkietyzacjaWebService\AnkietyzacjaWebServicece\Service1.asmx.cs:line 397"


Could You please tell me what am I missing here ?
Thanks a lot.
 

View 5 Replies View Related

Using GUID Fields As Primary Keys W/ Foreign Key Constraints

Nov 17, 2005

Ok, so I've broken down and decided to write myself an invoicing
program.  I'd like to use GUID fields as the Primary Keys in my
table.  Now, I basicly bill for two seperate items:

Deliverables and Services.

So, my Layout's gonna look something like

Create Table Invoice(
     ID UniqueIdentifier Primary Key,
     -- Other Data
);

Create Deliverable(
    ID uniqueidentifier Primary Key,
    ParentInvoice uniqueidentifier,
   -- Other data);
--...

Im sure there are probems with that as it's written feel free to edify me as to what they are. 

my questions are such:

1) Does a uniqueidentifier field automagically get a value?
2) If not how do I generate one in TSQL?
3) If so, what do I use to store my Foreign Keys.
4) How do I declare my Foreign key constraints?

View 12 Replies View Related

Lookup Table Foreign Key Null

May 1, 2007

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!

Table DDL:
CREATE TABLE [dbo].[EXTERNAL_FUNDING] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[project_id] [int] NOT NULL ,
[date_requested] [datetime] NULL ,
[source] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[type] [int] NULL ,
[amount] [money] NULL ,
[granted] [bit] NULL ,
[date_granted] [datetime] NULL
) ON [PRIMARY]

CREATE TABLE [dbo].[EXTERNAL_FUNDING_TYPE] (
[type] [nvarchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[id] [int] IDENTITY (1, 1) NOT NULL
) ON [PRIMARY]

View 2 Replies View Related

NULL Values Returned When Reading Values From A Text File Using Data Reader.

Feb 23, 2007

I have a DTSX package which reads values from a fixed-length text file using a data reader and writes some of the column values from the file to an Oracle table. We have used this DTSX several times without incident but recently the process started inserting NULL values for some of the columns when there was a valid value in the source file. If we extract some of the rows from the source file into a smaller file (i.e 10 rows which incorrectly returned NULLs) and run them through the same package they write the correct values to the table, but running the complete file again results in the NULL values error. As well, if we rerun the same file multiple times the incidence of NULL values varies slightly and does not always seem to impact the same rows. I tried outputting data to a log file to see if I can determine what happens and no error messages are returned but it seems to be the case that the NULL values occur after pulling in the data via a Data Reader. Has anyone seen anything like this before or does anyone have a suggestion on how to try and get some additional debugging information around this error?

View 12 Replies View Related

Integration Services :: SSIS Insert Non Null Value Into Null Rows

Jul 15, 2015

I have a flat file with the following columns

SampleID   Rep_Number   Product  Protein   Fat   Solids

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.

View 7 Replies View Related

SQL 2012 :: Explicit Columns Or NULL Foreign Keys?

Mar 19, 2014

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?

View 6 Replies View Related

Integration Services :: SSIS Reads Nvarchar Values As Null When Excel Column Includes Decimal And String Values

Dec 9, 2013

I have SQL Server 2012 SSIS. I have Excel source and OLE DB Destination.I have problem with importing CustomerSales column.CustomerSales values like 1000.00,2000.10,3000.30,NotAvailable.So I have decimal values and nvarchar mixed in on Excel column. This is requirement for solution.However SSIS reads only numeric values correctly and nvarchar values are set as Null. Why?

CREATE TABLE [dbo].[Import_CustomerSales](
 [CustomerId] [nvarchar](50) NULL,
 [CustomeName] [nvarchar](50) NULL,
 [CustomerSales] [nvarchar](50) NULL
) ON [PRIMARY]

View 5 Replies View Related

Null Values For Datetime Values Converted To '0001-01-01'

Mar 29, 2006

Hi

can somebody explain me how I can assign a NULL value to a datetime type field in the script transformation editor in a data flow task.
In the script hereunder, Row.Datum1_IsNull is true, but still Row.OutputDatum1 will be assigned a value '0001-01-01' which generates an error (not a valid datetime). All alternatives known to me (CDate("") or Convert.ToDateTime("") or Convert.ToDateTime(System.DBNull.Value)) were not successful.
Leaving out the ELSE clause generates following error: Error: Year, Month, and Day parameters describe an un-representable DateTime.




If Not Row.Datum1_IsNull Then

Row.OutputDatum1 = Row.Datum1

Else

Row.OutputDatum1 = CDate(System.Convert.DBNull)

End If



Any help welcome.

View 1 Replies View Related

T-SQL (SS2K8) :: Stored Procedure To Truncate And Insert Values In Table 1 And Update And Insert Values In Table 2

Apr 30, 2015

table2 is intially populated (basically this will serve as historical table for view); temptable and table2 will are similar except that table2 has two extra columns which are insertdt and updatedt

process:
1. get data from an existing view and insert in temptable
2. truncate/delete contents of table1
3. insert data in table1 by comparing temptable vs table2 (values that exists in temptable but not in table2 will be inserted)
4. insert data in table2 which are not yet present (comparing ID in t2 and temptable)
5. UPDATE table2 whose field/column VALUE is not equal with temptable. (meaning UNMATCHED VALUE)

* for #5 if a value from table2 (historical table) has changed compared to temptable (new result of view) this must be updated as well as the updateddt field value.

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved