473,396 Members | 1,942 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

inserting/updating multiple tables through stored procedures

Hi all,

I am having trouble to writing stored procedure to insert and update the 2 tables in sql server 2005. Here is my problem.

I have 2 tables with following columns.
TableName:BENEFIT_PDF
1)DOCUMENT_CK
2)EFFECTIVE_DATE
3)PDF_FILE_NAME
4)PDF_DISPLAY_NAME
5)PDF_IMAGE

another TableName: PLAN_PDF
1)DOCUMENT_CK
2)PLAN_ID
3)STATE

Here document_ck is the identity column which is autogenerated and refer to the PLAN_PDF.
EFFECTIVE_DATE and PDF_FILE_NAME FORM THE UNIQUE INDEX.

The first table stores the benefit detais as pdf file.(in the PDF_IMAGE column)

more than one state is associate with the benefitdetails.(thts why we have plan_pdf table)

like 2 states can have the same benefit details.PLAN_ID is unique in the table.

I need to provide a way to the client that he can able to populate these 2 tables through stored procedures.
i am wondering that should I write a single sp to do this or I need 2 sp's to acomplish this task.

I aslo need to provide the way to update these fields with the existing data at any time.
I am new to storedprocedures and I am confusing in mapping these tables and populate them.

Please help me.

thanks
Srini
Nov 13 '08 #1
13 42821
Delerna
1,134 Expert 1GB
Hi Shrinivas.
You wouldn't normally use a stored procedure, although it certainly can be done.
Stored procs may or may not be your best choice
A lot depends on what you are using as the front end for your users.

To do it with a stored proc, your front end will need to call it and pass the values to the stored proc through parameters.

Expand|Select|Wrap|Line Numbers
  1. create proc Update2Tables
  2.          @Action varchar(50),
  3.          @Doc int,
  4.          @Dte datetime,
  5.          @FileName varchar(50),
  6.          @DispName varchar(50),
  7.          @Image  varchar(50),
  8.          @Plan int,
  9.          @State  varchar(50)
  10. as
  11. IF @Action='Update'
  12. BEGIN
  13.      --SQL to update the 2 tables appropriately
  14. END
  15.  
  16. IF @Action='Insert'
  17. BEGIN
  18.      INSERT INTO BENEFIT_PDF
  19.      SELECT @Doc,@Dte,@FileName,@DispName,@Image
  20.  
  21.      INSERT INTO PLAN_PDF
  22.      SELECT @Doc,@Plan,@State 
  23. END
  24.  
  25. go
  26.  
You would call it something like this

exec Update2Tables 'INSERT',1,'2008-01-01','Test1','Test2','Image1',1,'STATE'


I have given you a basic idea here.
As I said Stored proc may not be the best way, it depends on a lot of things?
Depending on your front end it may not even be possible to use a stored proc for this.
Nov 14 '08 #2
ck9663
2,878 Expert 2GB
Try creating a trigger that will do the cascade insert for you...

-- CK
Nov 14 '08 #3
Hi Delerna,

If I do not use the stored procedure, I need to update these tables through my application right?

If so I need to join these 2 tables and do the insert/update from my application.

Can you send me sql query to join these 2 tables. Like I mentioned more than one state can have the same benefit details.

How can I do it? through join or any other way?

Please help me.
Nov 14 '08 #4
Hi Delerna,

I just confirmed with my team lead that we should make use of the stored procedure,Because the font end we are using is JAVA right now.We are just creating a helper class in java(which make use of these sp's in the database and call them) and giving it to the other vendor who can actually make use of that code.In the future if the client want to implement this service class with another .NET or some other language they can still use the sp's in the database and they can write their own business logic in the application from front end.

So I should stick to the stored procedures now.

the problem is that joining these two tables in the stored procedure.

My application is based on Health Care.Client wants a functionality that when the user login we should provide an option as Benefit details in the portal.When the user clicks in he should be presented all the pdf links that he is eligible for. Then user clicks on any of the link he should be able to view that pdf.

There are two tables which I created one is BENEFIT_PDF, second is PLAN_PDF.
As I said before more than one state can have the same benefit details.
and client should able to populate these tables with same benefit details but different states.
I am wondering how could I join these tables so that client can populate these tables.

Please send me the code for the joining these tables(with specified condition) in the stored procedure so that I can write front end application.

I am writing a helper class through which client can upload the customer benefit details into the database tables.
Nov 14 '08 #5
ck9663
2,878 Expert 2GB
Create an updateable view.

1. Create a view that join these tables.

2. Create an INSTEAD OF INSERT trigger on the view.

3. Let your trigger do the INSERT to two tables.

-- CK
Nov 15 '08 #6
Delerna
1,134 Expert 1GB
Ditto to what ck said.

But if you really want to use stored proc then you can easily call it with parameters from java. Then you just make the stored proce do whatever you want it to do using those parameters.

You can also use
Expand|Select|Wrap|Line Numbers
  1.    IF EXISTS (select * from TheTable where ConditionsToDetermineInsertOrUpdate)
  2.    BEGIN
  3.        --sql code to update
  4.    END ELSE BEGIN
  5.        --sql code to insert
  6.    END
  7.  
instead of the parameter to do inserts or updates.

Then you have the issue of returning the recordset back to JAVA for re-display.
Not overly difficult but ck's suggestion is the better option by far.

It is difficult to give you working queries for your particular question without having access to everything that you have access to. It's easier to come up with working solutions when you can see what you are working with.

You can see what you are working with, so you will need to find the solution.
We can help you along the way though.
Nov 17 '08 #7
[quote=Delerna]Ditto to what ck said.

Hi Delerna,

Thanks for your reply. Here I am doing some think like you said before.Please check the code I have writen.



# create proc Update2Tables
# @Action varchar(50),
# @Doc int OUTPUT,
# @Dte datetime,
# @FileName varchar(50),
# @DispName varchar(50),
# @Image image,
# @Plan int,
# @State varchar(50)
# as
# IF @Action='Update'
# BEGIN
# UPDATE BENEFIT_PDF SET EFFECTIVE_DATE=@Dte,PDF_FILE_NAME=@FileName,PDF_DI SPLAY_NAME=@DispName,PDF_IMAGE=@Image
# WHERE DOCUMENT_CK=@Doc
# UPDATE PLAN_PDF SET PLAN_ID=@Plan,STATE=@state
# WHERE DOCUMENT_CK=@Doc
# END
#
# IF @Action='Insert'
# BEGIN
# INSERT INTO BENEFIT_PDF VALUES(@Dte,@FileName,@DispName,@Image)
# SELECT @Doc=SCOPE_IDENTITY()
#
# INSERT INTO PLAN_PDF VALUES(@Plan,@State)
# SELECT DOCUMENT_CK=@Doc
# END
#IF @Action='Select'
# BEGIN
# SELECT PDF_IMAGE FROM BENEFIT_PDF WHERE DOCUMENT_CK=@Doc
# END




Does this code work for me? I am not handling any errors in the code.So please suggest me how to handle the errors in sp.

Here I am retrieving the pdf file based on identity column.

Yes I have to get the identity column from my application, from the stored proc and have to return that number to some other method.

Thanks in advance.
Nov 18 '08 #8
Delerna
1,134 Expert 1GB
Does this code work for me?
I don't know! when you run the front end and perform some tests, does it work the way you expect?
The code seems OK

please suggest me how to handle the errors in sp
One thing you could do is wrap the two inserts in a TRANSACTION
That way if either one fails you can roll both back to the state they were in before the transaction began.

Expand|Select|Wrap|Line Numbers
  1.    begin tran t1
  2.       insert etc etc
  3.       insert blah blah
  4.    if @@error<>0    
  5.    begin         
  6.       rollback tran t1        
  7.    end else begin         
  8.       commit tran t1   
  9.    end
  10.  
As for other error handling, you need to think of what could go wrong and try and cover it.
For example, with your 2 inserts
What if there is a record in the 2 tables and you want to insert a second,third,fourth... record into the PLAN_PDF table.
How are you going to handle that?
Nov 18 '08 #9
Hi Delerna,

I can upload the pdf file directly from the java application with out using the stored procedure.(using prepared statement in java)

But the problem here is I can not get the identity column value to my application which I need to return it to another application.

And one more thing when I tried to execute the sp's through my application I am only getting the out parameter incremented but the tables are not populating with values.

I tested by writing sp for a single insert function but the same thing its incrementing the identity column but values are not inserting in to the tables..

And the condition which you mentioned that if I need to populate the second table with different states for the same benefit details.

I am going crazy by thinking about that condition to implement but I could not move forward ..I simply stuck.

Please give me an idea how could I achieve that condition and also correct me what am I doing wrong with stored procedure that is not updating the tables.

The same java code works for me when I use it with out sp's.

Here I am sending the sp I have written.

USE [Test1]
GO
/****** Object: StoredProcedure [dbo].[Update2Tables] Script Date: 11/18/2008 16:43:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE Update2Tables
@Action varchar(50),
@Doc int OUTPUT,
@Dte datetime,
@FileName varchar(50),
@DispName varchar(50),
@Image image,
@Plan int,
@State varchar(50)
AS
IF @Action='Update'

DECLARE @update_error int

BEGIN TRY

BEGIN TRANSACTION

UPDATE BENEFIT_PDF SET EFFECTIVE_DATE=@Dte,PDF_FILE_NAME=@FileName,PDF_DI SPLAY_NAME=@DispName,PDF_IMAGE=@Image
WHERE DOCUMENT_CK=@Doc

UPDATE PLAN_PDF SET PLAN_ID=@Plan,STATE=@state
WHERE DOCUMENT_CK=@Doc

SELECT @update_error=@@ERROR
IF @update_error=0
BEGIN

COMMIT TRANSACTION

END
END TRY

BEGIN CATCH
IF @update_error<>0
BEGIN

ROLLBACK TRANSACTION

END

END CATCH

IF @Action='Insert'

DECLARE @insert_error int

BEGIN TRY

BEGIN TRANSACTION

INSERT INTO BENEFIT_PDF VALUES(@Dte,@FileName,@DispName,@Image)
SELECT @Doc=SCOPE_IDENTITY()

INSERT INTO PLAN_PDF VALUES(@Plan,@State)
SELECT DOCUMENT_CK=@Doc

SELECT @insert_error=@@ERROR
IF @insert_error=0
BEGIN

COMMIT TRANSACTION

END

END TRY

BEGIN CATCH
IF @insert_error<>0
BEGIN

ROLLBACK TRANSACTION

END

END CATCH

IF @Action='Select'
BEGIN

SELECT PDF_IMAGE FROM BENEFIT_PDF WHERE DOCUMENT_CK=@Doc

END

I can use a single try catch to handle the errors but here I just use the seperate
try catches to be more clear but I will change it later.

Please help me in this how could I achieve that same benefit details for different states.

Thanks in Advance.
Nov 19 '08 #10
Delerna
1,134 Expert 1GB
Very busy at the moment. It will look more thorougly when things quieten down a bit.
Nov 19 '08 #11
Oh it is ok. I am sorry I did not know that you were busy.Any way Thank you very much for letting me know that and when ever you will find a time you can give me a Reply.

Thanks a million.
Nov 20 '08 #12
Delerna
1,134 Expert 1GB
OK, got some free time now.
The INSERT INTO statements look wrong.

Something more like this
[code=sql]
INSERT INTO BENEFIT_PDF (NameOfField1,NameOfField2,NameOfField3,NameOfFiel d4)
VALUES(@Dte,@FileName,@DispName,@Image)
[code]

or this
Expand|Select|Wrap|Line Numbers
  1. INSERT INTO BENEFIT_PDF
  2. SELECT @Dte,@FileName,@DispName,@Image
  3.  
Afterthought
Maybe the parameters are empty and therefore the record is being created with the fields having no value just like the parameters.

Try using query analyser with this code
Expand|Select|Wrap|Line Numbers
  1.  exec Update2Tables 'Insert','2008-01-01','DocName.pdf','Display Name',1,'NSW'
  2.  
If the result of that is a record in the table with the field vales set correctly, then you know that the problem is in the front end and not the stored proc.

If the result is the same as when run from the front end then the problem is in the stored proc. In that case copy one of the insert statements and paste it into query analyser. Replace the parameters with values and try executing it.
I feel you will get an error message because they don't look right to me.

Whenever you have problems getting a large task to work, always break the problem down into smaller pieces and get that small piece working. Then you can put the working pieces back together into the larger task, knowing that that smaller piece is working.
Make sense?
Nov 20 '08 #13
Delerna
1,134 Expert 1GB
Now to the problem of inserting extra records into the PLAN_PDF table.

In the INSERT condition of the stored proc
If you provide enough info in your parameters you can check to see if a record already exists in BENEFIT_PDF if not then a record needs to be inserted into both tables.
If a record does exist then you only need to insert the record into the PLAN_PDF table.

You will, of course, need to be sure that the single record in BENEFIT_PDF properly references the multiple records in PLAN_PDF.

Hope these hints help you to solve your issues.
Nov 20 '08 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Ryan Hubbard | last post by:
I'm inserting a record into MySQL 4.0 using Visual Basic ADO. When using the AddNew and Update method I am unable to retrieve the value of a Auto incrment field (Yes I know I can MoveLast but this...
0
by: SQLServer007 | last post by:
25 more days until the "get it free" promotion runs out for xSQL Object (you can get it from http://www.x-sql.com) Here are just some of the great features packed in the product: - Compare SQL...
4
by: HeadScratcher | last post by:
We have written an application which splits up our customers data into their individual databases. The structure of the databases is the same. Is it better to create the same stored procedures in...
1
by: JLM | last post by:
I'm sure this has been addressed before, but I haven't found it yet. I have a form that I want to use to update multiple tables (with same/similar info). I can append a single table without much...
2
by: Tyro | last post by:
I have a form that needs to add a customer and customer history in one form. customer (custid) --->custdetail (custid) Is there anything easy in asp.net using DataAdapter, Dataset or DataTable...
1
by: Justin | last post by:
What is the best/easiest way to update multiple tables at a time? Can you recommend any tutorials? Thanks, Justin.
1
by: evandela | last post by:
Hi all... this is one part of ASP.net that i just dont understand... and GOD knows, i am trying. I have 2 tables, the first one called country and the second called product I create a datagrid...
2
by: monomaniac21 | last post by:
Hi all Using MySQL can anyone tell me how to most efficiently insert a collumn in 'table1' retrieve the id from this record and insert mutliple records into 'table2' with a collumn for the id in...
1
by: Rob Dob | last post by:
Hi, I have both a Customer and a Orders Table, the key field is CustomerID. I also have a DataGridView that uses a BindingSource created using a join between the Customers table and the Orders...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.