I have this stored procedure in SQL Server which I use in visual net to generate values for some table.
CREATE PROCEDURE grabardatos
#codigocliente int,
#nombre varchar(50),
#apellido varchar(50),
#sexo char(1),
#direcion varchar(50),
#telefono varchar(50),
#tipo varchar(50)
AS
BEGIN
INSERT INTO CLIENTES(Numero,Nombre,Apellido,Sexo,Direcion,Telefono,Tipo)
VALUES ( #codigocliente,#nombre,#apellido,#sexo,#direcion,#telefono,#tipo)
END
The parameter #codigocliente is the id of the table which, according to this code, has to be entered manually in visual net. How Can the id be autogenerated in the sql code of the stored procecure instead of being entered manually in visual net?
If the clientes table has an identity key, it will be automatically generated by SQL as part of the INSERT. You can then use ##identity to retrieve it's value.
The add the key to the table, you need to create a column
ALTER TABLE Add IdKey INT IDENTITY(1,1)
Note that during the INSERT, you cannot provide a value for this column...
Related
I am running a stored procedure that selects all the records from a database.
Select *
from dbo.Recods
where Active = 1;
but when I run this stored procedure, I do not get the identity key back, just the rest of the columns in the database.
Any ideas?
Thank you
The query to create the table is:
CREATE TABLE [dbo].[Tournaments] (
-- Add the parameters for the stored procedure here
Id int IDENTITY(1,1) PRIMARY KEY,
TournamentName nvarchar(50) NOT NULL,
EntryFee float,
Active int
);
How would I accomplish being able to insert an unknown number of records into the database using a single stored procedure call?
Say I have this table definition:
CREATE TABLE PHONE(
PhoneID int identity(1,1),
PhoneNumber varchar(20),
PersonID int
)
And I have the following insert stored procedure:
CREATE PROCEDURE dbo.usp_Phone_Insert
#PhoneNumber varchar(20),
#PersonID int
AS
INSERT
PHONE
VALUES
(#PhoneNumber, #PersonID)
How would I be able to transform this to insert any number of records in a single call to this stored procedure?
I have some blog posts with code samples that address this topic.
Performance Comparison of Singleton, XML, and TVP Inserts
http://sqlfool.com/2008/11/performance-comparison-of-singleton-xml-and-tvp-inserts/
Bulk Inserts with XML
http://sqlfool.com/2008/11/bulk-inserts-with-xml/
One-to-Many Inserts with Table-Valued Parameters
http://sqlfool.com/2008/11/one-to-many-inserts-with-table-valued-parameters/
HTH.
I have problem when I tried to update two tables in one Store Procedure I get the SqlException could some one help me
The INSERT statement conflicted with the FOREIGN KEY constraint "FK".
The conflict occurred in database "", table "dbo.Users", column
'userID'. The statement has been terminated.
ALTER PROCEDURE [dbo].[CreateProject]
#ProjectID UNIQUEIDENTIFIER,
#UserID UNIQUEIDENTIFIER,
#ProjectName NVARCHAR(50),
#Description NTEXT,
#EstStartDate DATETIME,
#EstEndDate DATETIME,
#StatusID SMALLINT,
#Priority SMALLINT
AS
INSERT INTO DBO.Projects VALUES
(#ProjectID,#ProjectName,GETDATE(),#Description,#EstStartDate,#EstEndDate,#StatusID,#Priority)
INSERT INTO Users_projects VALUES
(#ProjectID,#UserID)
Problem is with the Foreign Key of UserID. You need to insert UserId into the Users table first. Few pointers: "createProc" procedure generally should create the ProjectId and return as an OUTPUT parameter. Also, you may want to use username as input parameter and let the proc look up the UserId.
I've created a insert stored procedure with two tables like in the exapmle:
Table NameAge
CREATE TABLE [dbo].[Assignment3_NameAge]
(
userID int PRIMARY KEY IDENTITY(1,1),
Name varchar(255) NOT NULL,
Age int NOT NULL
)
Table Hobbies
CREATE TABLE [dbo].[Assignment3_Hobbies]
(
hobbiesID int Identity(1,1) Primary Key,
userID int Foreign Key references Assignment3_NameAge(userID),
hobbies varchar(255) NOT NULL,
)
Insert Stored Procedure
CREATE PROCEDURE [dbo].p_Assignment3Join_ins
#Name nvarchar(100),
#Age int,
#Hobbies nvarchar(100)
AS
INSERT INTO [TABLE].[dbo].[Assignment3_NameAge]
([Name]
,[Age])
VALUES (#Name,#Age)
INSERT INTO [TABLE].[dbo].[Assignment3_Hobbies]
([Hobbies])
VALUES (#Hobbies)
The problem is that when i run the stored procedure the table Hobbies has a null value for userid(the foreign key)
What am i doing wrong?
You should provide the key of the Assignment3_NameAge value you want to insert into Assignment3_Hobbies.
If you want the last inserted you can use SCOPE_IDENTITY() from SQL Server(if you're using SQL Server) or equivalent. It will give you the last inserted value from Assignment3_NameAge
I am guessing this is SQL Server based on the IDENTITY column. Correct?
The first insert creates a user, but there is no user ID being set on the insert of the hobby. You need to capture the identity value from the first insert to be used in the second insert. Have you gon over the system functions available?
You're not supplying a value for it, SQL won't automagically fill the value in for you even though you've created a Foreign Key relationship. It's your job to populate the tables.
Create Proc CrearNuevoAnuncio
#Titulo varchar(250),
#Precio int,
#Descripcion varchar(250),
#IDCategoria int,
#IDImagen int,
#Login varchar(200)
AS
INSERT INTO Anuncio VALUES(
#Titulo,
#Precio,
#Descripcion,
#IDCategoria,
#IDImagen,
#Login
)
The error is because the table anuncio has 1 more attribute: "idAnuncio". It's the primary key, and it's the indentity (autoincrement).
So, how can I handle this is the missing thing is an Identity. I don't want to pass that parameter from my front-end.
You need to specify the explicit list of columns in your insert statement:
INSERT INTO
Anuncio(Titulo, Precio, Descripcion, IDCategoria, IDImagen, Login)
VALUES
(#Titulo, #Precio, #Descripcion, #IDCategoria, #IDImagen, #Login)
Otherwise, SQL Server will try to insert values for ALL columns which fails here. It cannot insert a value into an IDENTITY column - that column will be set automatically by SQL Server upon inserting a new row, and is guaranteed to be unique.
Is the ID field of type "INT IDENTITY" ? In that case, you could access the value of the newly inserted ID like this:
DECLARE #NewID INT
SET #NewID = SCOPE_IDENTITY()
and possibly return it from the stored proc:
RETURN #NewID
Marc
You need to specify which value goes to which field.
INSERT INTO Anuncio (field1, field2, ...) VALUES (#Titulo, ...)