WHILE Statement To Loop Through A Table And Get The IDENT_CURRENT Values As It Inserts

Aug 14, 2007



Hi

I have a SSIS package that imports data into a staging table from an excel sheet (This works fine). From the staging tabler i want it to insert the values into my members table, take that unique indentityID that gets created and insert the other values into other tables for that member that was just created.

In the staging table, i have all the values for a single member. But the structure of the database needs all the values inserted into seperate tables. There is no conditions ID in my members table, so the member first has to be created and from there i need to use the newly created member's MemberID and insert the conditions into a seperate table using the MemberID

I have created some sample data that can be used. I think i have an idea of how to do it, but i'm not totally sure if it will work that way, i have however included it in the sample data.





Code Snippet
DECLARE @ImportedStagingData TABLE
(
ID INT IDENTITY(1,1),
Name VARCHAR(50),
Surname VARCHAR(50),
Email VARCHAR(50),
[Chronic Heart Failure] INT,
[Colon Cancer] INT
)
INSERT INTO @ImportedStagingData VALUES ('Carel', 'Greaves', 'CarelG@Email.com', 1,0)
INSERT INTO @ImportedStagingData VALUES ('Jamie', 'Jameson', 'JamieJ@Email.com', 1,1)
INSERT INTO @ImportedStagingData VALUES ('Sarah', 'Bolls', 'SarahB@Email.com', 0,1)
INSERT INTO @ImportedStagingData VALUES ('Bells', 'Scotch', 'BellsS@Email.com', 1,1)
INSERT INTO @ImportedStagingData VALUES ('Stroh', 'Rum', 'StrohR@Email.com', 0,0)
DECLARE @Conditions TABLE
(
ID INT IDENTITY(1,1),
Condition VARCHAR(50)
)
INSERT INTO @Conditions VALUES ('Chronic Heart Failure')
INSERT INTO @Conditions VALUES ('Colon Cancer')
DECLARE @Members TABLE
(
MemberID INT IDENTITY(1,1),
Name VARCHAR(50),
Surname VARCHAR(50),
Email VARCHAR(50)
)
DECLARE @memConditions TABLE
(
MemberID INT,
ConditionID INT
)
SELECT * FROM @ImportedStagingData
SELECT * FROM @Conditions
SELECT * FROM @Members
SELECT * FROM @memConditions
/* --- This is the part that i am battling with ---
DECLARE @CurrentValue INT
DECLARE @numValues INT
SET @numValues = (SELECT COUNT(ID) FROM @ImportedStagingData)
WHILE @numValues <> 0
BEGIN
INSERT INTO @Members
SELECT Name, surname, email
FROM @ImportedStagingData
GO
SET @CurrentValue = (SELECT IDENT_CURRENT('@ImportedStagingData'))
INSERT INTO @memConditions (MemberID), (ConditionID)
VALUES (@CurrentValue, --ConditionValue from @ImportedStagingData, all the values that have a 1)

@numValues = @numValues - 1
END
END
*/






All help will be greatly appreciated.

Kind Regards
Carel Greaves

View 5 Replies


ADVERTISEMENT

Parametized Inserts In A Loop

Mar 12, 2006

Hi,
I have a for next loop that I am using to write some data into a table.
The problem I have is one of the fields is an @parameter
The relevant bit of VB.net code is:
Dim dbpm_theDateTime As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
           
            dbConnection.Open()
            For intCounter As Integer = 0 To ds.Tables(0).Rows.Count - 1
          
                querystring = "Insert into tblActionsToDo ([TheDT], [username]) VALUES (@theDateTime, '" & username & "’)â€?
           
                dbpm_theDateTime = New System.Data.SqlClient.SqlParameter
                dbpm_theDateTime.ParameterName = "@theDateTime"
                dbpm_theDateTime.Value = tmpstrDT
                dbpm_theDateTime.DbType = System.Data.DbType.DateTime
                dbCommand.Parameters.Add(dbpm_theDateTime)
               
                dbCommand.CommandText = querystring
                                
                rowsAffected = dbCommand.ExecuteNonQuery
               
               
            Next
The first time through the for next loop, everything works fine.  The next time though I get an error that @theDateTime has already been defined.  To be fair, it is true; but how do I get round this?  I've tried making the @parameter a string so that I can manipulate it as "@parameter" & intcounter, and thus have a uniquely-named varaible for every loop, but it doesn't work.
thanks for any pointers

View 1 Replies View Related

Set-based INSERTS Rather Than A Loop

Jan 20, 2006

I have a table with a series of rows for period 1 - these always exist

drop table tblmain
create table tblmain (period int, rfreq int, pfreq int)
insert tblmain (period , rfreq , pfreq )
select 1 , 1 , 1
union all
select 1 , 1 , 3
union all
select 1 , 1 , 6
union all
select 1 , 3 , 3
union all
select 1 , 3 , 6
union all
select 1 , 6 , 6
union all
select 1 , 6 , 12


select * from tblmain
period rfreq pfreq
1 1 1
1 1 3
1 1 6
1 3 3
1 3 6
1 6 6
1 6 12
*/


I need to do a whole lot of inserts with incremented period values up to and including
a number assigned in a different table, FMaxes based on JOINing the two tables on the rfreq column


CREATE TABLE FMaxes (RFreq INT , MaxFINT)
insert FMaxes (RFreq , MaxF)
select 1 , 5
union all
select 3 , 3
union all
select 6 , 2


select * from FMaxes
RFreq MaxF
1 5
3 3
6 2


Ive been scratching my head for hours trying to figure out a set-based approach rather than a loop
solution which I could produce

The desired result would be inserts from period 2 onwards - result set below



select * from tblmain

period rfreq pfreq
1 1 1
1 1 3
1 1 6
1 3 3
1 3 6
1 6 6
1 6 12

2 1 1
2 1 3
2 1 6
2 3 3
2 3 6
2 6 6
2 6 12

-- no period 3 or higher for rfreq value 6 because table FMaxes holds an MaxF value of 2 etc
3 1 1
3 1 3
3 1 6
3 3 3
3 3 6

-- no period 4 or higher for rfreq value 3 because table FMaxes holds an MaxF value of 3 etc
4 1 1
4 1 3
4 1 6

5 1 1
5 1 3
5 1 6

Thanks in advance

View 4 Replies View Related

IDENT_CURRENT And Empty Table

Sep 18, 2005

Hi,can somebody explain me, why the IDENT_CURRENT from an empty table is 1?After insert of the first record it is still 1 (assuming that start valueis 1) which is okay. But if i check the IDENT_CURRENT from a newly createdtable the result should be NULL, or not?bye,Helmut

View 10 Replies View Related

How Do I Retrieve The IDENT_CURRENT Value Of A Table Using An SqlDataSource?

Dec 8, 2005

Hi
I am trying to get the last ID value of a table. 
The following code worked when a SQLConnection object was used, how do I achieve the same result using an SQLDataSource?
this.sqlSelectCmd2 = new System.Data.SqlClient.SqlCommand("SELECT IDENT_CURRENT('Assets')",sqlConnection1);
sqlConnection1.Open();
int nID = Convert.ToInt32( this.sqlSelectCmd2.ExecuteScalar() ) ;
nID++;
dc.FocusedRow["ID"] = nID.ToString();
Cheers
Pen
 

View 1 Replies View Related

Error Executing A Sql Statement Against A Table With Null Date Values

Apr 10, 2008

We are just upgrading a server from 2000 to 2005 and we are getting the message below when we execute a sql statement against a table with a date field with null values:


"Error converting data type DBTYPE_DBTIMESTAMP to datetime."

View 3 Replies View Related

SQL Server 2008 :: Store Long Values To Be Used In (IN) Statement In Separate Table?

Jul 14, 2015

I have several reports that are looking for a code within a certain set of codes or ranges. The specific list of codes to be including is determined by the end user. Currently my "IN" statement can be a hundred lines, listing several ranges, lists of specific codes, etc. I am constantly getting asked what codes does it include, is this code included, etc. Sometimes they'll give me a printed 10 page list of codes and want me to compare to what I have included in the report. Not ideal in the slightest.

What I'd like to do is have a table or a file of some kind somewhere where the end user can view the codes contained, add new ones, and delete ones they no longer want. Then I'd like to be able to just reference that file in my IN statement. Leaving the responsibility of listing the correct codes on them.

View 9 Replies View Related

Loop Though Table Using RowID, Not Cursor (was Loop)

Feb 22, 2006

I have a table with RowID(identity). I need to loop though the table using RowID(not using a cursor). Please help me.
Thanks

View 6 Replies View Related

How Do I Script INSERTS From An ASP Membership Table Onto Live Server Table

Aug 7, 2007

Hi,I would have used the aspnet membership tool to auto-create all the ASP.NET membership tables.  However, the hosting company don't allow remote connections which meant I had to create the tables by hand, scripting the tables using script to CREATE using management studio.However, I noticed one of the tables has data without any users: aspnet_SchemaVersions, which causes an error when trying to log onto my site.The fix is to make sure the table has the 4-5 rows of data in it (which is missing off the live server).  Its just a few rows of data, but I want to script the inserts for each row so I don't have to type them in using myLittleAdmin (the host's web version of management studio). Can anyone point me in the right direction?

View 3 Replies View Related

Is Having A Trigger That Inserts A Row In Table 'A', When A Row In Same Table Is Inserted By ADo.Net Code?

Oct 13, 2006

I want to insert a row for a Global user  in Table 'A' whenever ADO.Net code inserts a Local user row into same table. I recommended using a trigger to implement this functionality, but the DBA was against it, saying that stored proecedures should be used, since triggers are unreliable and slow down the system by placing unecessary locks on the table. Is this true OR the DBA is saying something wrong? My thinking is that Microsoft will never include triggers if they are unreliable and the DBA is just wanting to offload the extra DBA task of triggers to the programmer so that a stored procedure is getting called, so he has less headache on his hands.Thanks

View 2 Replies View Related

How To Use Loop Statement

Jul 24, 2006

I have a table which contains 170K of customer_numbers. How can I write a query (loop) to create 340 tables or excel files which contains 500 customer numbers each.

Thanks for your assistance in advance.

View 3 Replies View Related

Collecting Values Into A Variable In A Loop

Mar 13, 2006

Dear All,

I’m trying to collect values from a query into a single variable within a loop, like so:

WHILE condition is true
BEGIN

SET @intLoop = @intLoop + 1

@myString = @myString + ‘, ‘ + (SELECT companyName FROM @tblTheseComp WHERE id = @intLoop

END

For some reason though the @myString does not collect up the values, but will equal NULL at the end of the loop.

If however I simple do

WHILE condition is true
BEGIN

SET @intLoop = @intLoop + 1

@myString = (SELECT companyName FROM @tblTheseComp WHERE id = @intLoop
END


Then I get the last value from the query as expected.

Can anyone explain why this might be?

Thanks in advance!

View 7 Replies View Related

SQL Server 2012 :: Create Dynamic Update Statement Based On Return Values In Select Statement

Jan 9, 2015

Ok I have a query "SELECT ColumnNames FROM tbl1" let's say the values returned are "age,sex,race".

Now I want to be able to create an "update" statement like "UPATE tbl2 SET Col2 = age + sex + race" dynamically and execute this UPDATE statement. So, if the next select statement returns "age, sex, race, gender" then the script should create "UPDATE tbl2 SET Col2 = age + sex + race + gender" and execute it.

View 4 Replies View Related

T-SQL (SS2K8) :: Create Union View To Display Current Values From Table A And All Historical Values From Table B

May 6, 2014

I 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

View 9 Replies View Related

How To Loop Through Select Statement

Jul 4, 2012

What I wanted to do is I want to loop through each select result and at the same time use the result to do something while in a loop.

While (select field1,field2,field3 from table 1)
BEGIN
select count(*) as field4 from table1 where field1(current_record)>3
update table1 set field2(current_record)=field4
END

something like that...How do I do this?

View 5 Replies View Related

Problem With Setting Variable Values In A Loop

Sep 11, 2007

In a stored procedure that I'm fixing, there is a problem with assigning variable values inside a loop. The proc is using dynamic SQL and if statements to build all these statements, but I'm having to add a new variable value to it that is throwing it out of whack.

This is the current structure:

SET @MktNbr = 10

WHILE @MktNbr < 90

BEGIN

DECLARE@sqlstmt varchar(1000)

SET @Market = '0' + CONVERT(char(2),@MktNbr)

SET @sqlstmt = 'SELECT (columns)
INTO dbo.table' + @Market + '
FROM #table
WHERE marketcode = ''' + @Market + '''
IF @MktNbr = 50
BEGIN
SET @MktNbr = 51
END
ELSE
IF @MktNbr = 51
BEGIN
SET @MktNbr = 52
END
ELSE
IF @MktNbr = 52
BEGIN
SET @MktNbr = 55
END
ELSE
IF @MktNbr = 55
BEGIN
SET @MktNbr = 60
END
ELSE
BEGIN
SET @MktNbr = @MktNbr + 10
END
EXEC (@sqlstmt)


END


I'm probably having a blonde moment, but I'm trying to replace the if statements with this:

SET @MktNbr =
CASE
WHEN @MktNbr = 10 THEN 20
WHEN @MktNbr = 20 THEN 30
WHEN @MktNbr = 30 THEN 40
WHEN @MktNbr = 40 THEN 50
WHEN @MktNbr = 50 THEN 51
WHEN @MktNbr = 51 THEN 52
WHEN @MktNbr = 52 THEN 55
WHEN @MktNbr = 55 THEN 60
WHEN @MktNbr = 60 THEN 70
WHEN @MktNbr = 70 THEN 80
WHEN @MktNbr = 80 THEN 81
ELSE @MktNbr END

Clearly it's wrong because the proc bombs every time with a duplicate table error.

It has been suggested to me that I should hold these market values in an external table. This sounds reasonable but I'm ashamed to admit that I don't know how I'd implement that. Can someone maybe give me a nudge in the right direction?

View 14 Replies View Related

Assigning Variable Values Via Loop Using Different Datatypes

Apr 10, 2008

Hi all,

I need some help regarding a conversion in a Script Task.

I am reading my variable values from a database with a sql task, the table has two columns, variable and variableValue.
Looping through the recordset and setting the different variables works well, with two links:
http://blogs.conchango.com/jamiethomson/archive/2005/02/09/SSIS_3A00_-Writing-to-a-variable-from-a-script-task.aspx
http://sqlblog.com/blogs/andy_leonard/archive/2007/10/14/ssis-design-pattern-read-a-dataset-from-variable-in-a-script-task.aspx

setting the variable value only works well if the package variable is defined as string, because the db field is a varchar, trying to assign an integer for example brings up an error.

Therefor I tried something like CType:
Dts.Variables("MyVar").Value = CType(MyRecordsetField,String), where the target datatype should be depending on the variable datatype instead of being assigned as a constant.

Could someone give me a hint to handle this?

Thanks in advice!

Cheers
Markus

View 3 Replies View Related

For Each Loop Failure When Some Values In Recordset Are NULL

Sep 15, 2006

I have a for each loop container that is performing various tasks as it loops through a record set. Some of the values from the recordset are NULL at times and this causes the FELC to fail because it is unable to map the variables that have NULL values.

Is there something I can set to have it accept the NULLS or something I can change about the variables themselves. This is valid data that still needs to be processed. There are other attributes that have data in the record.

Here are samples of my error messages:

Error: ForEach Variable Mapping number 19 to variable "User::varTransactionReference" cannot be applied.

Error: ForEach Variable Mapping number 20 to variable "User::varFlowStartDate" cannot be applied.

Error: ForEach Variable Mapping number 26 to variable "User::varCancelFee" cannot be applied.



Thanks in advance.

SK



View 2 Replies View Related

Slow INSERTs On A Table

Apr 5, 2007

Hello all. I've got a problem with really slow INSERTs on one (and only one) of the tables in a database. For example, using SQL Management Studio, it takes 4 minutes and 48 seconds to insert 25 rows. There are only about 8 columns in the table and only about 1500 records. All the other tables in the database are very fast for inserts.

Another odd thing uniquely associated with INSERTs on this table: prior to inserting the 25 new rows of data, SQL Management Studio tells me that it inserted 463 rows of data which I know did not happen. Here's the INSERT statement:

INSERT INTO FieldOps(StudySiteID
, QA_StructureID
, Notes
, PersonID)
SELECT DISTINCT StudySiteKey
, QA_StructureKey
, SampleComments1
, '25'
FROM ScriptOutput_Nitrate
WHERE (ScriptOutput_Nitrate.StudySiteKey IS NOT NULL)

and SQL Management Studio (eventually) says:
(463 row(s) affected)
(463 row(s) affected)

(25 row(s) affected)

The table has an index on the primary key (INT data type with auto increment). I tried running the following code to fix things but it made no difference:

USE [master]
GO
ALTER DATABASE [FieldData] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

use FieldData
GO
DBCC CHECKTABLE ('FieldOps', REPAIR_REBUILD) With ALL_ERRORMSGS
GO

USE [master]
GO
ALTER DATABASE [FieldData] SET MULTI_USER WITH ROLLBACK IMMEDIATE
GO

I'm guessing that the problem might be related to the index (??). I don't know... Does anyone here have a suggestion as to what I should do to fix this problem.

View 9 Replies View Related

T-SQL With Inserts In Various Table In One Transaction

Mar 29, 2008

Dear All,
I developed an application years ago where I have to insert records in multiple table from asp.net page during registration process with one button click. I have seperate Insert statements and then i have to select Identity column value and insert into another table as a foriegn key and so on.
I want to run all these SQL insert in one statement or Stored procedure. becuase currently, if one of insert statemetn fails, I have no way to roll back previous inserts and start over again.

Any advice or sample T-SQL Where I can insert in Table A, and then read the identity from Table A and insert in Table B, in one single Transaction, so if it fails at end of Transaction, i want to roll back the all the inserts and updates in table(s).

Thanks,

View 13 Replies View Related

Loop In Select Lookup Statement

Apr 19, 2005

Hello All,

Below is a simple Select statement performing a Lookup into a SQL database and returning the columns (associated with the Row) in to Cells on an eForm. The issue I have is there are 42 rows (which go up and down) and do not feel like writing 42 select statements.

select RiskDescriptor, RiskImpactLowDescriptor, RiskImpactMediumDescriptor, RiskImpactHighDescriptor
from [Risk Descriptors]
where [RiskDescriptor ID] in (1)
order by [RiskDescriptor ID];
<<1@Cell104>>
<<2@Cell105>>
<<3@Cell106>>
<<4@Cell107>>


I would like to add a loop, adding 1 to the RiskDescriptor ID and 4 to the Cells. So on second pass in the loop:
RiskDescriptor ID = 2
<<1@Cell108>>
<<2@Cell109>>
<<3@Cell110>>
<<4@Cell111>>

Third pass in the loop:
RiskDescriptor ID = 3
<<1@Cell112>>
<<2@Cell113>>
<<3@Cell114>>
<<4@Cell115>>
and so on.

The Until portion of the loop can be hardcode (42 in this example) but would rather use an EOL or Query the DB for the total number of RiskDescriptor ID. This way when the DB changes (ID's go up or down) the SQL Statement does not need to be notified.

It is a JDBC call from within the eForm.

I would appreciate any help on how to format a loop in a SQL Statement

View 2 Replies View Related

Cursors - Looping Through A Table And Do Inserts From It

Dec 5, 2006

I've been looking online and cannot find any help  / resources with this so I brought it here :D
 I'm looking for help in creating a Cursor (this will be inside a SP) that will loop through the records of a "Table" (Temporary or Retrieved) and for each row that is looped through I can use it's values to do inserts against a few other tables.
 Any resources / help would be great! I work best by example.

View 12 Replies View Related

Export Data From Table As SQL Inserts

Jul 21, 2005

Hi,

I have data in an old database I would like to capture for my new
system but I dont have the original insert scripts.  Is there a
tool (in SQL Server 2000 or thirdparty) that will help me export the
data as SQL inserts?

Thanks

jr.

View 1 Replies View Related

Selecting From Table With Lots Of Inserts

Mar 19, 2008

Hi,

I am working on an application to analyse down time on a production line system. The system has about 40 rows inserted per minute. The inserts are coming from about 10 different stations.

I need to a analyse the downtime between each insert from each station. The plan is to copy the data to another database on a different server so as not to affect the live system that is being updated by the production line.

However the initial requirement was to do this at night while the production line was down but now they want the data to be updated every 3 hours which means performing this huge query while the production line is bombarding the DB with inserts.

I am wondering what is the best way of doing this. Is there any way I can limit the abount of processor this proceedure will take.

Any advice appreciated,

Thanks,
Sean

View 2 Replies View Related

DB Engine :: Concurrent Inserts Into Same Table

Jun 26, 2015

I have a table into which the inserts will be done by multiple users at the same time;

The table has a primary key, non clustered, on unique id; each insert will have unique id, which is a seqence generated number, so they are always different for different transactions.

Is this possible to set the settings of sql server in such a way, that these inserts are done at the same time i.e. during insert by one user that table is not locked so that other inserts can take place at the same time as well?

View 6 Replies View Related

How To: Create A Table That Only Allows Inserts And Deletes.

Feb 26, 2008


I need to create a table that only allows records to be inserted or deleted. Once the record has been created it can only be deleted. Is there anyway to configure a table in this manner?

Table Definition

USE [DB_AUTOMATED_PACKAGING_SYSTEM]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TBL_PCL_LENS_DATA](
[SerialNumber] [varchar](50) NOT NULL,
[ProcessedDate] [datetime] NOT NULL,
[Filename] [varchar](50) NOT NULL,
[CartonLabelImage] [image] NOT NULL,
[ExpirationDateLabelImage] [image] NOT NULL,
[LabelSetLabelImage] [image] NOT NULL,
[ReplyCardLabelImage] [image] NOT NULL,
[TextFile] [ntext] NOT NULL,
CONSTRAINT [PK_TBL_PCL_LENS_DATA] PRIMARY KEY CLUSTERED
(
[SerialNumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
SET ANSI_PADDING OFF

View 5 Replies View Related

Bug With Ident_current

Jan 29, 2004

Hello,
I have tried developped a stored proc that is using the ident_current('tablename') function to get the last Identity ID.

It was working fine. I drop and recreate the table (which reset the ID) and found that the ident_current said that the last Identity Id used was 1. The problem was that the table was empty. I insert a record and try it again. It said again that the last Identity ID was 1. After the insertion if the first record, everything is fine...

I would like to know if you know a way get 0 when the table is empty and 1 when there is only one identity id that have been used.

Thank

Felix Pageau
fpageau@str.ca

You can test the functionnality with the following code:

create table identCurrentBugExeample(IDnumber int IDENTITY(1,1), aChar char(1))
Declare @count as int
set @count = (select count(IDnumber) from identCurrentBugExeample)

--Print the number of record in the table
print @count

--Supposed to print 0 because there isn't any identity values that has been used
print ident_current('identCurrentBugExeample')
insert identCurrentBugExeample(aChar) values('a')

--Print 1 because the last identity used is 1
print ident_current('identCurrentBugExeample')
insert identCurrentBugExeample(aChar) values('a')

--Print 2 because the last identity used is 2
print ident_current('identCurrentBugExeample')
drop table identCurrentBugExeample

View 8 Replies View Related

Calculate Total Tuition By Accumulating Column Values ( Loop?)

Jun 3, 2004

I am trying to create a procedure which will calculate the total tuition
This process involves 3 tables.
Contract table has tuition information which is all $100 (set price).
Discount table has discount type and discount percentage (ex. 0.3) on each discount type.
ContractDiscount table have contract number and discount number to connect both tables


I think I need to create a loop since some contract gets more than one discount.
I have to calculate and get result nee to be like this

total_tuition = (tuition - discountPer * tuition) - this has to be a loop condition

Do you have any suggestion ?

Thanks

View 3 Replies View Related

Master And Child Table Inserts At A Time.

May 15, 2007

I have a situation here. Please
advice me on this.



I have a master table and a child
table. They have a PK and FK relationship. The master table has an identity
column with auto increment set to true. This map as a FK in the child table. My
questions are:

Can I have a single form to insert a new record into
master and child table at the same time?This has to be accomplished without stored
procedures. Can it be done?Is it possible to do this with a single insert query?
If yes, can it be done with sql data source or
dataset or tableadapters’?Please point me towards appropriate link for doing
so.





Thank you.

I am currently using SQL Server
2005 and VS 2005.

View 1 Replies View Related

Creating Stored Procedure That Inserts Value In Table

Feb 13, 2008

I am using vwde2008 and created db and table. i want to create a stored procedure that will insert values. I am bit lost on how write this.
this is my table info
table = BusinessInfo
Columns = BusinessID, BusinessName, BusinessAddress
how can i create a stored procedure ?

View 1 Replies View Related

Inserts And Updates To A Table That Contains A Unique Key Constraint

Nov 5, 2007

I am looking for pros and cons for the following scenarios:

When a table contains a unique key constraint is it viable to always do an insert and immediately check the @@ERROR value and if @@ERROR states a duplicate key exception then perform an update statement?

Another possible solution would be to always check if the key exists and then do the insert / update based upon that result. This method will always require two steps.

View 4 Replies View Related

Check Constraint - Compare Sum Of Two Values In One Table Against Values Located In Another Table

Jul 26, 2014

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.

View 2 Replies View Related

Transact SQL :: Update One Table Based On Another Table Values For Multiple Values

Apr 26, 2015

I 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







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