473,659 Members | 2,934 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

inserting/updating multiple tables through stored procedures

6 New Member
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:BENEF IT_PDF
1)DOCUMENT_CK
2)EFFECTIVE_DAT E
3)PDF_FILE_NAME
4)PDF_DISPLAY_N AME
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 storedprocedure s and I am confusing in mapping these tables and populate them.

Please help me.

thanks
Srini
Nov 13 '08 #1
13 42901
Delerna
1,134 Recognized Expert Top Contributor
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,'200 8-01-01','Test1','Te st2','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 Recognized Expert Specialist
Try creating a trigger that will do the cascade insert for you...

-- CK
Nov 14 '08 #3
srinivas gandrath
6 New Member
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
srinivas gandrath
6 New Member
Hi Delerna,

I just confirmed with my team lead that we should make use of the stored procedure,Becau se 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 Recognized Expert Specialist
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 Recognized Expert Top Contributor
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
srinivas gandrath
6 New Member
[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_N AME=@FileName,P DF_DISPLAY_NAME =@DispName,PDF_ IMAGE=@Image
# WHERE DOCUMENT_CK=@Do c
# UPDATE PLAN_PDF SET PLAN_ID=@Plan,S TATE=@state
# WHERE DOCUMENT_CK=@Do c
# END
#
# IF @Action='Insert '
# BEGIN
# INSERT INTO BENEFIT_PDF VALUES(@Dte,@Fi leName,@DispNam e,@Image)
# SELECT @Doc=SCOPE_IDEN TITY()
#
# INSERT INTO PLAN_PDF VALUES(@Plan,@S tate)
# SELECT DOCUMENT_CK=@Do c
# END
#IF @Action='Select '
# BEGIN
# SELECT PDF_IMAGE FROM BENEFIT_PDF WHERE DOCUMENT_CK=@Do c
# 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 Recognized Expert Top Contributor
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,fo urth... record into the PLAN_PDF table.
How are you going to handle that?
Nov 18 '08 #9
srinivas gandrath
6 New Member
Hi Delerna,

I can upload the pdf file directly from the java application with out using the stored procedure.(usin g 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_IDENTIFI ER 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_N AME=@FileName,P DF_DISPLAY_NAME =@DispName,PDF_ IMAGE=@Image
WHERE DOCUMENT_CK=@Do c

UPDATE PLAN_PDF SET PLAN_ID=@Plan,S TATE=@state
WHERE DOCUMENT_CK=@Do c

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,@Fi leName,@DispNam e,@Image)
SELECT @Doc=SCOPE_IDEN TITY()

INSERT INTO PLAN_PDF VALUES(@Plan,@S tate)
SELECT DOCUMENT_CK=@Do c

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=@Do c

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

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

Similar topics

1
2756
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 icreases the update time by a factor of 10 and when your talking about 200,000 inserts its way to long). Is there a way to insert the record into multiple tables in one statement where you can use the value of the auto incremented field as the...
0
1977
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 Server objects (databases, tables, views, stored procedures, user defined data functions etc.) accross servers. - view and print dependencies; - generate color coded scripts for any object in the database or many of them at once (many configurable...
4
1402
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 each database or have them in one central location and use the sp_executesql and execute the generated the SQL statement. Thank you. Mayur Patel
1
1585
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 problem, but have never tried to update more than one table. thanks, jlm
2
1274
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 to do this? What's the best practice for doing this kind of stuff?
1
2572
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
1548
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 and have to custom write the sql Select command Up to this point it all works fine... the hitch is that i also want to be able to update the damned thing... here is the declaration of my datasource... what do I need to do? please I am a newbie...
2
4411
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 'table1' which links the two recordsets
1
4112
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 table. Everything displays correctly and when I double click on a row within the datagrid I then open up a tabbed form that contains a detailed view of the bindingsource record selected ( which was created using a join ). The user at this point...
0
8427
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8332
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8525
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8627
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6179
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2750
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.