Insert Into Using Stroed Procedure

May 23, 2008

hi,

my question is how to insert  into multiple tables using stored procedure?

here is my code whcich didnt worked :/USE [DBCars]

GO

/****** Object: StoredProcedure [dbo].[insertuser] Script Date: 05/23/2008 23:13:05 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

ALTER procedure [dbo].[insertuser]

(@Make nchar(10),@Model nchar(10),@City nchar(10),@SellerID varchar(50),@MileAge nchar(10),@Year_Model int)

as

insert into tbcar values(@Make,@Model,@City,@SellerID,@MileAge,@Year_Model);

GO

as (@thumb_id varchar(50),@image_id varchar(50),@car_id int)

insert into tbimages(@thumb_id,@image_id,@car_id)

View 2 Replies


ADVERTISEMENT

Stroed Procedure Problem

Dec 17, 2001

I am having a problem with the following SQL code. It will be a stored proc once it works.

I have a variable @CardNumber. The last line of the SELECT Statements says: Where Card.CardNumber=1234/*@cardNumber*/

The Query works when I have the number hard coded on this line. It does not work when I try to use the variable by uncommenting it and removing the 1234.

Please help. This has to be simple!

Thanks!!!

- Mike

Declare @Balance money
Declare @Fee money
Declare @CustomerNumber int
Declare @TransAmount MONEY
Declare @TransType Int
Declare @CardNumber int

SELECT DISTINCT
@TransAmount=100,
@CardNumber=1234,
@Balance=1000,/*Card.CustomerBalance,*/
@CustomerNumber=Card.CustomerNumber
From dbo.Card Card
Where Card.CardNumber=1234/*@cardNumber*/

Select
@Fee=1.50/*SC.ATMWithdrawalFee*/
From dbo.ServiceCharge SC
Where SC.CustomerNumber=@CustomerNumber

If @Balance > @TransAmount + @Fee /*@transamount*/ /* MAKE SURE THAT THEY HAVE*/
/* ENOUGH MONEY INCLUDING FEE*/
Update Card
Set CustomerBalance=(@Balance - @TransAmount - @Fee)
Where Card.CardNumber=1234

View 3 Replies View Related

Stroed Procedure Code

Sep 29, 2005

Hi:
I was working in SQL MS Enterprise Manager. I opened my DB and then tried to write a new Stored procedure(Stroed Procedure-->right click-->new procedure--> blank SP window). I copied some .sql code from VB. It had a beggining line like:

" If exists in Sytemobjects(newprocedure)
drop procedure newprocedure

Create proc newprocedure
as "
----

Now when I am copying this code in Enter Manager, the If part just vanishes and the code starts(opening from Enter Manager) from

Create proc newprocedure.

What is the catch here. I tried to see all other SPs in my DB and none of them has the If part.

What is the wrong. Why it does not take the If part.

View 2 Replies View Related

USing A Sql Stroed Procedure ..how To Best Access Data??

Apr 1, 2004

I know how to use a reader to read in my values but how do u use other methods when dealing with a stored procedure which deals in both single tables and multiple tables......

View 3 Replies View Related

Problem With Stroed Procedure (URGENT)

Jul 13, 2001

Hello All.

DEFINATION:

I've a Stored Procedure that accepts 3 parameters. User can supply values for any 1 or more parameters (depends on the user choice, if he needs to search on one column then he needs to supply only one parameter, if he needs to search on two columns then he needs to supply two parameters, and so on ...

The query inside the Stored Procedure is written dynamically, I mean depending on the parameters provided by the user, a dynamic query is stored in a VARCHAR variable (suppose @ssql). In the last the dynamically written query is executed with following simple statement :

Exec (@ssql)

PROBLEM:

Now the problem is when my Programming team calls this Stroed Procedure from an ASP page, it never returns any Rows in the Recordset Object, though it runs perfect from the Query Analyzer with the same Execution Statement and Paramether Values. It seems that the ASP page is unable to recognize the Field (Column Names) reffered in the Query written dynamically inside the Stored Procedure. But if we write the Static Query in the Stroed Procedure, it always works fine.

Can someone identfy what problem is this about, or may be someone has faced this problem in past also. I would really appreciate if someone can help me in this ...

Regards.
Aamir

View 3 Replies View Related

Stray ' And Stroed Procedures

Apr 18, 2008

Is there a way to deal with stray ' in strings, such as: 'SQL Team's', in stored procedures inputs without using variables. Normally I'd correct this by putting + char(39) + ' after that stray apostrophe but when I do that within a stored procedure it spits back an error about the + sign.

Can anyone help?

Just to be clear, the problem I’m dealing with is like the following:

EXEC Database.dbo.StoredProcedure 'SQL Team's'

And I’ve the following as a solution, but it returns “Incorrect syntax near '+'.�:

EXEC Database.dbo.StoredProcedure 'SQL Team' + char(39) + 's'

View 4 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

Help With INSERT Procedure

Nov 30, 2006

Hello,I have a procedure which INSERTS a new record in two tables [Content] and [ContentLocalized] given [ContentName] and [ContentCulture].Here are the table structures:   <Content>          |----- [ContentId]   Type=UniqueIdentifier   PK          |      [ContentName]    Type=NVarChar(100)          |          |     <ContentLocalized>          |           [ContentLocalizedId]   Type=UniqueIdentifier   PK          | -------> [ContentId]   Type=UniqueIdentifier   FK          |           [ContentCulture]   Type=NVarChar(5)          |           [ContentHtml]   Type=NVarChar(MAX)  WHAT I AM MISSING:    > If in <Content> THERE IS a record with the same [ContentName] then this record will be used AND:           If in <ContentLocalized> for the given [ContentName] THERE IS NO such [ContentCulture] then a new will be created with [ContentCulture] and [ContentHtml]           If in <ContentLocalized> for the given [ContentName]
THERE IS such [ContentCulture] then its [ContentHtml] will be replaced by the given [ContentHtml]    > If in <Content> THERE IS NOT a record with the same [ContentName] then:           A new <Content> record will be created with [ContentName] and a new <ContentLocalized> record will be created with [ContentCulture] and [ContentHtml].I know I didn't get there yet.Could somebody help em out?I am posting the INSERT Store Procedure as I have now:      1 SET ANSI_NULLS ON
2 GO
3 SET QUOTED_IDENTIFIER ON
4 GO
5 ALTER PROCEDURE [dbo].[Content_CreateContentByNameAndCulture]
6 @ContentName NVARCHAR(100),
7 @ContentCulture NVARCHAR(5),
8 @ContentHtml NVARCHAR(MAX)
9 AS
10 BEGIN
11 SET NOCOUNT ON;
12 DECLARE @ContentId UNIQUEIDENTIFIER;
13 SET @ContentId = NEWID();
14 INSERT dbo.Content
15 (
16 ContentName
17 )
18 SELECT
19 @ContentName;
20 SELECT @ContentId;
21 INSERT dbo.ContentLocalized
22 (
23 ContentId,
24 ContentCulture,
25 ContentHtml
26 )
27 SELECT
28 @ContentId,
29 @ContentCulture,
30 @ContentHtml;
31 END
32 GO
33
34
35
Thanks,Miguel 

View 2 Replies View Related

Help Me With An Insert Procedure, Please

Apr 6, 2008

hi,
i have a table UserVisits with VisitID (primary) , UserName, UserID, PictureID, NewComment bit
when a user addes a comment to one picture, the NewComment column is modified to true, and when user with userName = "zuperboy90" visits again the picture with id = 4, the NewComment is set to false, something like asp.net when a post is changed or has replys
here is my stored procedure witch doesn't work, please help me with it  1 ALTER PROCEDURE dbo.PictureVisit
2
3 @PictureID int,
4 @UserName nvarchar(255),
5 @UserID uniqueidentifier
6
7 AS
8
9 IF EXISTS(SELECT VisitID
10 FROM UserVisits
11 WHERE UserID = @UserID AND PictureID = @PictureID)
12
13 UPDATE UserVisits
14 SET Modified = 0
15 WHERE UserID = @UserID
16
17 ELSE
18
19 INSERT INTO UserVisits
20 (UserName,
21 UserID,
22 PictureID,
23 Modified)
24
25 VALUES
26 (@UserName,
27 @UserID,
28 @PictureID,
29 0)
 this works only if user visits first time the picturewhen same user visits second time that picture (so in UserVisits already exists a row with UserName = "zuperboy90" and PictureID = 4, i get errorhow can i format this stored procedure to do what i need?many thanks
 

View 2 Replies View Related

Insert Procedure

Feb 3, 2008

Hi,
I am want to create an insert stored procedure. It looks like so


CREATE PROCEDURE dbo.sp_insert_member

@mbrFirstName nvarchar(15), @mbrLastName nvarchar(15), @mbrStreetAdress nvarchar(15), @mbrPostalAdress nvarchar(15), @mbrTelephoneNumber nvarchar(15),

@mbrTelePhoneJob nvarchar(15), @mbrEmail nvarchar(15)

AS

INSERT INTO dbo.member(mbrFirstName, mbrLastName, mbrStreetAdress, mbrPostalAdress, mbrTelphoneNumber, mbrTelephoneJob, mbrEmail)

VALUES ('mbrFirstName', 'mbrLastName', 'mbrStreetAdress', 'mbrPostalAdress', 'mbrTelephoneNumber', 'mbrTelephoneJob', 'mbrEmail')

GO


When I run it, I get the following message

Msg 207, Level 16, State 1, Procedure sp_insert-member, Line 10
Invalid column name 'mbrStreetAdress'

mbrStreetAdress exists in the SQL-server. Does anyone know what is wrong?


View 5 Replies View Related

Stored Procedure Insert

Nov 7, 2006

Hi,
I am having trouble inserting 2 fields in a row using a stored procedure.
This works fine:
Exec ('Insert Into NumbersPull (Number)'+ @SQL)
but when I try to insert another value into field 2 it errors out:
I try this:
Exec ('Insert Into NumbersPull
(Number,resultID) Select ('+ @SQL
+ '),' + @resultID'
)
and get this error:
ERROR: Line 2: Incorrect syntax near ')'.
Thanks,
Doug

View 3 Replies View Related

INSERT INTO With Stored Procedure

Feb 27, 2007

Having problem do INSERT values to my SQL DB with an StoredProcedure. SELECT works fine.
My StoredProcedure :
CREATE PROCEDURE insert_test
@id  int ,@Rubrik char(25), @Info  char(60) , @Datum datetime
ASINSERT INTO test_news(ID, Rubrik, Info, Datum) VALUES (@id, @Rubrik, @Info, @Datum)GO
The StoredProcedure  works fine in the SQL Query Analyzer
 
My Code;
int num= 1234; string rub = "KLÖKÖLKÖLKÖL"; string ino = "slökdjfkasdkfjsdakf";SqlConnection myConnection = new SqlConnection("server='SOLDANER\DAER'; trusted_connection=true; database='SeWe'");
SqlCommand myCommand = new SqlCommand("insrt_test", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add( "@id",num);myCommand.Parameters.Add( "@Rubrik",rub );myCommand.Parameters.Add( "@Info", ino);myCommand.Parameters.AddWithValue( "@Datum", DateTime.Now );
 Even tried AddWithValues
Dont get any error.....

View 3 Replies View Related

Insert Stored Procedure Help

Oct 31, 2007

OK I have a stored procedure that inserts information into a database table.  Here is what I have so far:
I think I have the proper syntax for inserting everything, but I am having problems with two colums.  I have Active column which has the bit data type and a Notify column which is also a bit datatype.  If I run the procedure as it stands it will insert all the information correctly, but I have to manually go in to change the bit columns.  I tried using the set command, but it will give me a xyntax error  implicating the "=" in the Active = 1 How can I set these in the stored procedure?1 SET ANSI_NULLS ON
2 GO
3 SET QUOTED_IDENTIFIER ON
4 GO
5 -- =============================================
6 -- Author:xxxxxxxx
7 -- Create date: 10/31/07
8 -- Description:Insert information into Registration table
9 -- =============================================
10 ALTER PROCEDURE [dbo].[InsertRegistration]
11
12 @Name nvarchar(50),
13 @StreetAddress nchar(20),
14 @City nchar(10),
15 @State nchar(10),
16 @ZipCode tinyint,
17 @PhoneNumber nchar(20),
18 @DateOfBirth smalldatetime,
19 @EmailAddress nchar(20),
20 @Gender nchar(10),
21 @Notify bit
22
23 AS
24 BEGIN
25 -- SET NOCOUNT ON added to prevent extra result sets from
26 -- interfering with SELECT statements.
27 SET NOCOUNT ON;
28
29 INSERT INTO Registration
30
31 (Name, StreetAddress, City, State, ZipCode, PhoneNumber, DateOfBirth, EmailAddress, Gender, Notify)
32
33 VALUES
34
35 (@Name, @StreetAddress, @City, @State, @ZipCode, @PhoneNumber, @DateOfBirth, @EmailAddress, @Gender, @Notify)
36
37 --SET
38 --Active = 1
39
40 END
41 GO
 

View 8 Replies View Related

Help With Insert Stored Procedure

Nov 17, 2007

I'm trying to make sure that a user does not allocate more to funds than they have to payments. Here is what my stored procedure looks like now: I listed th error below
ALTER PROCEDURE [dbo].[AddNewFundAllocation] @Payment_ID Int,@Receipt_ID Int,@Fund_ID Int,@Amount_allocated money,@DateEntered datetime,@EnteredBy nvarchar(50)ASSELECT     (SUM(tblReceiptsFunds.Amount_allocated) + @Amount_allocated) AS total_allocations, Sum(tblReceipts.AmountPaid) as total_paymentsFROM         tblReceiptsFunds INNER JOIN                      tblReceipts ON tblReceiptsFunds.Receipt_ID = tblReceipts.Receipt_IDWHERE tblReceipts.Payment_ID=@Payment_IDIF (total_allocations<total_payments)INSERT INTO tblReceiptsFunds ([Receipt_ID],[Fund_ID],[Amount_allocated],DateEntered,EnteredBy)

Values (@Receipt_ID,@Fund_ID,@Amount_allocated,@DateEntered,@EnteredBy)

ELSE BEGIN
PRINT 'You are attempting to allocate more to funds than your total payment.'
END I get the following error when I try and save the stored procedure:
Msg 207, Level 16, State 1, Procedure AddNewFundAllocation, Line 26
Invalid column name 'total_allocations'.
Msg 207, Level 16, State 1, Procedure AddNewFundAllocation, Line 26
Invalid column name 'total_payments'.

View 6 Replies View Related

Using Insert Stored Procedure With C#

Dec 5, 2007

I'm trying to insert the details in the "registration form" using stored procedure to my table. My stored procedure is correct, but I dunno what is wrong in my code or I dunno whether I've written correct code. My code is below. Please let me know what is wrong in my code or my code is itself wrong..... protected void RegisterSubmitButton_Click(object sender, EventArgs e)    {               SqlConnection conn = new SqlConnection("Server=ACHUTHAKRISHNAN; Initial Catalog=classifieds;Integrated Security=SSPI");        SqlCommand cmd;        cmd = new SqlCommand("registeruser", conn);        SqlParameter par = null;        par= cmd.Parameters.Add("@fname", SqlDbType.VarChar, 30);        par.Value = RegisterFirstNameTextBox;        par = cmd.Parameters.Add("@lname", SqlDbType.VarChar, 30);        par.Value = RegisterLastNameTextBox;        par = cmd.Parameters.Add("@uname", SqlDbType.VarChar, 30);        par.Value = RegisterUserNameTextBox;        par = cmd.Parameters.Add("@pwd", SqlDbType.VarChar, 20);        par.Value = RegisterPasswordTextBox;        par = cmd.Parameters.Add("@email", SqlDbType.VarChar, 40);        par.Value = RegisterEmailAddressTextBox;        par = cmd.Parameters.Add("@secque", SqlDbType.VarChar, 50);        par.Value = RegisterSecurityQuestionDropDownList;        par = cmd.Parameters.Add("@secans", SqlDbType.VarChar, 40);        par.Value = RegisterSecurityAnswerTextBox;        try        {            conn.Open();            cmd.ExecuteNonQuery();        }        catch (Exception ex)        {            throw new Exception("Execption adding account. " + ex.Message);        }        finally        {            conn.Close();    } }

View 2 Replies View Related

Two Insert In One Stored Procedure

Jan 28, 2008

Hi,
I have two tables "people' and "dept". What I need is a stored procedure to insert into both tables.
I need first, insert into "people" table, and then, insert into "dept" table since the first insert returns people id(peo_id), which
is an input parameter for "dept" table.
Here is my stored procedure, but I got error:Create PROCEDURE [dbo].[insert_people]
@peo_last_name varchar(35),
@peo_mid_initial varchar(1) = null,@peo_first_name varchar(10),
@peo_address1 varchar(50) = null,
@peo_city varchar(30) = null,
@peo_state varchar(2) = null,
@peo_zip varchar(10) = null,
@peo_ph1 varchar(30) = null,
@peo_ph2 varchar(30) = null,
@peo_email varchar(40) = null,
@dept_id int, @peo_id int
 
AS
SET @peo_id = (INSERT INTO people (peo_last_name, peo_mid_initial, peo_first_name, peo_address1, peo_city, peo_state, peo_zip, peo_ph1, peo_ph2, peo_email)
VALUES (@peo_last_name, @peo_mid_initial, @peo_first_name, @peo_address1, @peo_city, @peo_state, @peo_zip, @peo_ph1, @peo_ph2, @peo_email))
INSERT INTO dept (dept_id, peo_id)
VALUES (@dept_id, @peo_id)
GO
Could somebody help out?
Thanks a lot!

View 3 Replies View Related

Insert Using Stored Procedure

Apr 9, 2008

I have a table with UserID, UserName, UserPassword
I have a stored procedure as follows:ALTER PROCEDURE UserInsert
@UserName varchar(50),
@UserPassword varchar(50)
AS
BEGIN
INSERT Users (UserName, UserPassword)
VALUES (@UserName, @UserPassword)
END
I have a GridView bound to the Users Table and seperate textboxes (UserName, UserPassword) on a webform. 
Couple of Questions...
1. how and/or what code do I use to execute the Stored Procedure to insert what is in the textboxes into the Table using a button click event?
2. Since UserID is autogenerated on new records....does UserID need to be in the code?
Many Thanks

View 1 Replies View Related

Using Insert Into ... Stored Procedure...

Feb 21, 2006

Hi,
I need to insert a new user if the user (user_login) does not exist in the table (abcd_user) using a stored procedure.
I created a stored procedure called "insert_into_abcd_user". Here is the complete strored procedure...
CREATE PROCEDURE [dbo].[insert_into_abcd_user] (     @first_name  [VARCHAR](30),      @last_name  [VARCHAR](30),      @email  [VARCHAR](60),      @user_login [VARCHAR](50))  AS INSERT INTO [dbo].[abcd_USER] ([first_name],  [last_name],  ,  [user_login])VALUES (@first_name,  @last_name,  @email,  @user_login)
I need to to insert a new user if the user (user_login) does not exist int the table (abcd_User).
Any one shade on my code?
I appreciate your help in advance.
 
-- Srinivas Gupta.

View 2 Replies View Related

Store Procedure On Insert

Mar 29, 2001

Hello,
I need to write a store procedure that

when someone inserts a blank space("") into all the columns of
a table, the store procedure will set the blank space to
zero (0).
thanks

View 3 Replies View Related

INSERT INTO ... From A Stored Procedure

Sep 17, 2004

For example:

INSERT INTO Table_1
SELECT
Source_Table.Field_1,
Source_Table.Field_2,
Source_Table.Field_3,
???? OUTPUT parameter returnet from a stored procedure ???????
FROM Source_Table

Is posible this ?

View 2 Replies View Related

Insert Procedure From Excel

Sep 29, 2007

Hi all

I need to create a stored procedure that will insert from an Excel document. And I'm not exaclty sure of how to do that.


CREATE PROCEDURE [Insert_ActiveSuspensions]

AS
INSERT INTO [GamingCommissiondb].[dbo].[License_SuspensionsView]
([TM #],
[FIRSTNAME],
[LASTNAME],
[SS #],
[REASONFORSUSPENSION],
[ENDDATE]
[BEGINDATE])


SELECT
[TM#],
[LASTNAME],
[FIRSTNAME],
[SSN#],
[NOTES],
[DATEOFCONDITIONAL]

FROM "C:Documents and SettingsDesiree StevensonMy DocumentsTerminationInserts.xls"
IF @@Error <> '0'



is this correct??

View 7 Replies View Related

INSERT INTO.. A Stored Procedure!

Aug 30, 2006

I have created a stored procedure which simply inserts two records into a table. Here is my stored procedure:-
//BEGIN
ALTER PROCEDURE [dbo].[pendingcol]
@cuser varchar(100)
AS
Declare @sqls nvarchar(1000)

SELECT @sqls = 'INSERT INTO' + @cuser + '(UserName, Pending) VALUES ("recordone", "recordtwo")'

EXECUTE sp_executesql @sqls

RETURN
//END

This is the code i am using to call my stored procedure using VB.NET:-
//BEGIN
'variables
Dim user As String
user = Profile.UserName

'connection settings
Dim cs As String
cs = "Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|friends.mdf;Integrated Security=True;User Instance=True"
Dim scn As New SqlConnection(cs)

'parameters
Dim cmd As New SqlCommand("pendingcol", scn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@cuser", SqlDbType.VarChar, 1000)
cmd.Parameters("@cuser").Value = user

'execute
scn.Open()

cmd.ExecuteNonQuery()

scn.Close()
//END

Now when i execute this code i get an error point to cmd.ExecuteNonQuery() that says
" The name "recordone" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted. "

As far as i can see theres nothing wrong with the VB code, im guessing that the problem lies somewhere in my stored proc!

Can anyone please enlighten me on where i may be going wrong?
Cheers

View 10 Replies View Related

Store Procedure(insert)

Jan 21, 2008

He All
I Ive got this table [Person] And I want to Insert some value on the stored procedure. here's my code






SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:<Author,,Name>
-- Create date: <Create Date,,>
-- Description:<Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[InsertPerson] 'Davids','davids@gmail.con','David','Scott','21-06-1983','(073) 101 1232','(040) 858 4544','(040) 898 7412',1,'830621 6521 082','Male',3,2,'scotty',332,4,getdate(),getdate(),'Sedick'
(
@varUserName varchar(100),
@varEmailAddress varchar(100),
@varFirstName varchar(256),
@varSurname varchar(256),
@varDateofBirth varchar(100),
@varCellPhoneNumber varchar(20),
@varWorkTelephoneNo varchar(20),
@varHomeNumber varchar(20),
@intIDTypeId int,
@varIDNumber varchar(100),
@varGendervarchar(10),
@intOccupationId int,
@intStatusId int,
@varPassword varchar(100),
@intLoginCount int,
@intLostPasswordCount int,
@varUpdatedBy varchar(256)
)
AS
BEGIN
INSERT INTO [Person]
([UserName],
[EmailAddress],
[FirstName],
[Surname],
[DateofBirth],
[CellPhoneNumber],
[WorkTelephoneNumber],
[HomeTelephoneNumber],
[IDTypeId],
[IDNumber],
[Gender],
[OccupationId],
[StatusId],
[Password],
[LoginCount],
[LostPasswordCount],
[DateCreated],
[DateUpdated],
[UpdatedBy])
VALUES
(@varUserName,
@varEmailAddress,
@varFirstName,
@varSurname,
@varDateofBirth,
@varCellphoneNumber,
@varWorkTelephoneNo,
@varHomeNumber,
@intIDTypeId,
@varIDNumber,
@varGender,
@intOccupationId,
@intStatusId,
@varPassword,
@intLoginCount,
@intLostPasswordCount,
getdate(),
getdate(),
@varUpdatedBy)
END
GO

View 2 Replies View Related

Using NOT EXISTS In An INSERT Procedure

Jul 23, 2005

I am using the following code to insert records into a destination tablethat has a three column primary key i.e. (PupilID, TermID &SubjectGroup). The source table records all the pupils in a school with(amongst other things) a column (about 50) for each subject the pupilmight potentially sit. In these columns are recorded the study groupthat they belong to for those subjects. The destination table holds arecord per pupil per subject per term, against which the teacher willultimately record the pupils performance.The code as shown runs perfectly until the operator tries to insert aselection of records that include some that already exist. What I wouldlike it to do is, record those, which do not exist and discard theremainder. However, whenever a single duplicate occurs SQL rejects thewhole batch. I know that my solution will probably involve using the‘NOT EXISTS’ expression, but try as I might I cannot get it to work. Tofurther complicate things, the code is being run from within VBA usingthe RunSQL command.The variables ‘strFieldName’, ‘strGroup’ & ‘strTerm are declared at thestart of the procedure and originate from options selected on an Accessform.INSERT INTO dbo.yInterimReportData (PupilID, LastName, FirstName,TermID, SubjectGroup) SELECT PupilID, LastName, FirstName," & "'" &strTerm & "'" & "," & "'" & strGroup & "'" & "FROM dbo.Pupils WHERE (" &strFieldName & " = " & "'" & strGroup & "')Any Ideas?RegardsColin*** Sent via Developersdex http://www.developersdex.com ***

View 1 Replies View Related

Can I Use A Stored Procedure For INSERT In SqlDataSource?

Jun 20, 2006

Hello,
I have created a web page with a FormView that allows me to add and edit data in my database.  I configured the SqlDataSource control and it populated the SELECT, INSERT, UPDATE and DELETE statements.  I've created a stored procedure to do the INSERT and return to new identity value.  My question is this: Can I configure the control to use this stored procedure?  If so, how?  Or do I have to write some code for one of the event handlers (inserting, updating???)
Any help would be appreciated.
-brian

View 1 Replies View Related

Select + Insert Into + Stored Procedure. Please Help Me.

Oct 14, 2006

So I have simply procedure: Hmmm ... tak sobie myÅ›lÄ™ i ...

Czy dałoby radę zrobić procedurę składową taką, że pobiera ona to ID w
ten sposob co napisalem kilka postow wyzej (select ID as UID from
aspnet_users WHERE UserID=@UserID) i nastepnie wynik tego selecta jest
wstawiany w odpowiednie miejsca dalszej procedury ?[Code SQL]ALTER procedure AddTopic    @user_id int,    @topic_katId int,    @topic_title nvarchar(256),    @post_content nvarchar(max)as    insert into [forum_topics] (topic_title, topic_userId,topic_katId)    values (@topic_title, @user_id, @topic_katId)       insert into [forum_posts] (topic_id, user_id,post_content)    values (scope_identity(), @user_id, @post_content)Return And I want to make something more. What I mean - in space of red "@user_id" I want something diffrent. I make in aspnet_Users table new column uID which is incrementing (1,1). In this way I have short integer User ID (not heavy GUID, but simply int 1,2,3 ...). I want to take out this uID by this :SELECT uID from aspnet_Users WHERE UserId=@UserId.I don't know how can I put this select to the stored procedure above. So I can have a string (?) or something in space of "@user_id" - I mean the result of this select query will be "@user_id".  Can anyone help me ? I tried lots of ways but nothing works.

View 6 Replies View Related

Insert Or Update With Stored Procedure

Dec 27, 2006

I'm doing this more as a learning exercise than anything else.  I want to write a stored procedure that I will pass a key to it and it will look in the database to see if a row exists for that key.  If it does, then it needs to update the row on the DB, if not, then it needs to insert a new row using the key as an indexed key field on the database.for starters can this even be done with a stored procedure?if so, can someone provide some guidance as to how?thanks in advance,Burr

View 5 Replies View Related

Can I INSERT INTO A Temp Tbl Twice In One Stored Procedure

Mar 15, 2007

In my stored procedure I need to select some data columns and insert them into a #temp tbl and then select the same data columns again using a different from and put them into the same #temp tbl. It sounds like a union, can I union into a #temp tbl?
Any help here is appreciated.

View 4 Replies View Related

Need Help In Creating Stored Procedure Insert

Apr 2, 2007

Want help in creating the stored procedure of company where id is the PrimaryKey in the table companymaster which is created in sql server 2005.1 ALTER PROCEDURE companyinsert
2
3 @companyid int,
4 @companyname varchar(20),
5 @address1 varchar(30)
6
7 AS
8
9 INSERT INTO companymaster
10 ( companyname, address1)
11 VALUES (@companyname,@address1) Procedure or Function 'companyinsert' expects parameter '@companyid', which
was not supplied.

The id is to be created autogenerate in the sequence number.There should be no duplicated companyname with different ids in same table.Apart from the above error can anyone pls give me or tell me the code or modify the stored procedure according to the above..thanxs....    

View 5 Replies View Related

How To Invoke Insert Stored Procedure

Apr 3, 2007

Feeling really dumb tonight - below is my stored procedure and code behind which completes (it puts "completed" in TextBox4) but does not insert anything into database.
Questions:1) do in need to include the primary key field in the insert stored procedure?2) do I need a DataAdapter to actually get it running and open and close the connection? STORED PROCEDURE running on SQL 2000 server: ______________________________________
CREATE PROCEDURE newuser003.InsertCompanyInfo
@CS_CompanyName nchar(100),@CS_City nchar(500),@CS_Phone varchar(20)
AS
INSERT into tblCompanyInfo_Submit(CS_CompanyName, CS_City, CS_Phone)VALUES ('@CS_CompanyName', '@CS_City', '@CS_Phone')RETURN
C# CODE BEHIND: ______________________________________________________ 
public partial class ContractorSubmision : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {       }    protected void Button1_Click(object sender, EventArgs e)    {        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["localhomeexpoConnectionString2"].ConnectionString);        SqlCommand cmd = new SqlCommand("CompanyInfoSubmit", con);        cmd.CommandType = CommandType.StoredProcedure;        cmd.Parameters.AddWithValue("@CS_CompanyName", TextBox1.Text);        cmd.Parameters.AddWithValue("@CS_City", TextBox2.Text);        cmd.Parameters.AddWithValue("@CS_Phone", TextBox3.Text);        TextBox4.Text = "Completed";    }}
 

View 5 Replies View Related

Insert Does Not Take Place If Stored Procedure Is Run From ASP.NET

May 8, 2007

Hello,
I am having an issue with the insert command in a stored procedure in SQL Server 2005. The procedure is designed to generate a Customer number and insert an initial value (a delivery charge) into an order table. Finally, it returns the customer number back to the caller. When I execute the stored procedure from SQL Server Management Studio, it works perfectly. However, when I call it from ASP.net, the procedure properly generates a Customer Number and returns it to my application, but the insert never takes place. Can someone help me figure out why it won't insert?
My ASP.Net (C#) code is here: SqlDataSource dsSelect = new SqlDataSource();
dsSelect.ConnectionString = ConfigurationManager.ConnectionStrings["obeConn"].ConnectionString;
dsSelect.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
dsSelect.SelectCommand = "getTempCustNo";

DataView reader = (DataView)dsSelect.Select(DataSourceSelectArguments.Empty);

Session["CustNo"] = reader[0]["CustNumber"].ToString().Trim();
Session["PriceCode"] = reader[0]["PriceCode"].ToString().Trim();
Session["orderNo"] = reader[0]["OrderNo"].ToString().Trim();  
  My stored procedure is here:ALTER PROCEDURE [dbo].[getTempCustNo]
AS
BEGIN
declare @CustNo int;
declare @prodDesc VARCHAR(max);
declare @prodNo int;
declare @stdPrice float;
declare @orderNo int;
declare @priceCode int;

-- populate values
SELECT @custNo = ISNULL(MAX(OD_CUSTNO)+1, 100000000), @prodNo = 999, @orderNo = 1, @priceCode = 1000
FROM [dbo].[tblOrderDet]
WHERE OD_CUSTNO >= 100000000;

-- get the price of our product
SELECT @stdPrice = PR_RATE_1
FROM tblPrices
WHERE PR_PRODNO = @ProdNo
AND PR_RCDCOD = @priceCode;

-- get the description
SELECT @ProdDesc = PM_PRDESC + ' ' + PM_VOLUME FROM dbo.tblPromas WHERE PM_PRODNO = @ProdNo;

--Add a delivery charge to the customer's order table
INSERT INTO tblOrderDet (OD_ORDRNO, OD_CUSTNO, OD_PRODNO, OD_QUANTITY, OD_ORG_QUANTY, OD_PRICE, OD_DESCR, OD_LOW)
VALUES (@orderNo, @CustNo, @prodNo, 1, 0, @stdPrice, @prodDesc, 'N');

--Return the customer values
SELECT @custNo AS 'CustNumber', @orderNo AS 'OrderNo', @priceCode AS 'PriceCode';
END 

View 3 Replies View Related

Execute Insert Stored Procedure

Jan 22, 2008

Hi,
 I am strugling to execute a insert stored procedure on a button click. The stored procedure is taking values from a  temp table and inserting them into a identical table. The procedure is expecting 1 value from a Query string, the stored procedure works as expected when hard coded.
 
Im completely new to this and have no idea where to begin, i have been looking through the forums for several hours and am still none the wiser.
 
please can someone point me in the right direction

View 13 Replies View Related

Using A Stored Procedure To Insert A New Record

Apr 7, 2004

ok I have a stored procedure......
I pass in the variables that are requried....What is the best way to add a record
using my stored procedure in VB.net code in a button click event......
How might i do this with a data reader,,data adapter.....OR What.......................Do I need to declare all my varaibles I am adding to this new record in the line after POSCODE or can vb.net do this without a parameter statemetn




CREATE procedure dbo.Appt_AddAppt
(
@ClinicID int,
@AccountNum nvarchar(10),
@DOS nvarchar(12),
@POSCODE nvarchar(5)
)
as
Insert into Clinic_Appointments (ClinicID,AcctNumber,DateOfService,PlaceOfService,PlaceOfServiceID)
Values (@ClinicID,@AccountNum,@DOS,@POSCODE,@ClinicID)



GO

View 4 Replies View Related







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