Can you help me with this stored procedure? My problem is: when I create an account, my stored procedure works perfectly, but when I create a second account in the table evidenta_stundenti_materii, my previous id of account gets doubled.
How many times does it insert when I create an account :
in tbl_utilizatori : once
in tbl_studenti: once
in tbl_evidenta_stundenti: the previous id and the current id are re-inserted when I create the 2nd account
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[insertAnewAccAndANewStudent]
(#email varchar(30),
#parola varchar(30),
#nume varchar(30),
#prenume varchar(30),
#adresa varchar(30),
#nrTelefon varchar(30),
#conectat bit,
#idRol int,
#idSpecializare varchar(30))
AS
BEGIN
INSERT INTO dbo.tbl_utilizatori (email, parola, nume, prenume, adresa, nr_telefon, conectat, id_rol)
VALUES (#email, #parola, #nume, #prenume, #adresa, #nrTelefon, #conectat, #idRol)
IF (#idRol = '1')
BEGIN
DECLARE #id_utilizator int = ##identity
INSERT INTO dbo.tbl_studenti
VALUES (#id_utilizator, #idSpecializare, '0', '1')
END
INSERT INTO dbo.[tbl.evidenta_stundeti_materii] (id_utilizator, id_materie, id_specializare)
SELECT a.id_utilizator, b.id_materie, a.id_specializare
FROM dbo.tbl_studenti a
INNER JOIN dbo.tbl_materii b ON a.id_specializare=b.id_specializare
WHERE a.id_specializare = #idSpecializare
END
Bad English, can provide ss for a better understand problem
Related
I have the below data available in a table
DECLARE #AddressTbl As Table (ID int identity,Address varchar(100))
INSERT INTO #AddressTbl
VALUES ('State:AndhraPradesh,Dist:Prakasam')
Next time when I enter the same value I should be notified that this value exists in the table.
For this I will use an sp with warning message that the data is available. But I want how to implement the logic to compare the data.
Create Procedure usp_InsertAddress
(
#Address varchar(100)
)
AS
DECLARE #ID INT
SELECT #ID=(SELECT ID FROM #AddressTbl WHERE Address = #Address)
IF #ID IS NULL
BEGIN
INSERT INTO #AddressTbl
VALUES ('State:AndhraPradesh,Dist:Prakasam')
END;
I may enter the address like 'Dist:Prakasam,State:AndhraPradesh'
and there may be some blank spaces also. So need to parse the address and check the key and values.
I will use permanent table instead of table variable.
Appreciate your help.
You can use if exists for check. Or you can add unique CONSTRAINT in your table. The UNIQUE constraint ensures that all values in a column are different. This will return error if you are trying to insert duplicate value.
Create Procedure usp_InsertAddress
(
#Address varchar(100)
)
AS
if exists(SELECT ID FROM #AddressTbl WHERE Address = #Address)
begin
select 'Value is Already Exist in Table'---For Warning
end
else
BEGIN
INSERT INTO #AddressTbl
VALUES ('State:AndhraPradesh,Dist:Prakasam')
select 'Value Inserted Sucessful'---For Success
END;
create procedure SP_insert_test #name varchar(20), #emailid varchar(20), #trainer_name varchar(50), #training_date varchar(50), #training_time varchar(50), #gymname varchar(50) , #success int out as
begin
if(
select
count(id)
from
Add_Booking_Fitness_Training
where
training_time = #training_time) > 11 print N'Number of Booking Is Complete for this time and date plz book other time';
else
insert into
Add_Booking_Fitness_Training(memeber_name, member_emailid, trainer_name, training_date, training_time, gymname)
values
(
#name,
#emailid,
#trainer_name,
#training_date,
#training_time,
#gymname
)
SELECT
SCOPE_IDENTITY()
set
#success = 1;
end
begin
set
#success = 0;
end
i have an table in which i want to insert data on give time only 12 member can insert at that time after that they get message list is full plz change the time for inserting i have create procedure its working when its reach number of 12 than its show me message but when i change the time its also show me the same message and not insert any data into database
like 26/04/2018,'6:00' i want to insert this value only 12 time after 12 this show me a message about the limit of number is reach plz change (time)
Create table Add_Booking_Fitness_Training ( id int identity primary key,
memeber_name varchar(20),
member_emailid varchar(20),
trainer_name varchar(50),
training_date varchar(50),
training_time varchar(50),
gymname varchar(50))
i just want to inserting a value into this table only 12 time for a give time like (6:00) if the number of inserting value reach to 12 than its show me the message number of values insert is reach to 12 please change the time.
i want input the value into table only 12 time for a give time 6:00Am when the value is insert into table 12 time than message come up for change time than insert value for change time
Honestly, I am completely guessing here, I still don't really know what you're asking.
I think the OP's statement of "i want input the value into table only 12 time for a give time 6:00Am when the value is insert into table 12 time than message come up for change time than insert value for change time." means that they only want a time to appear in the table up to 12 times. If it appears more than that, the INSERT fails.
This can be achieved with a check constraint and a scalar function. So, as a very simple example:
USE Sandbox;
GO
--Create a very simple table
CREATE TABLE SampleTable (TrainingTime datetime2(0));
GO
--Create the scalar function
CREATE FUNCTION TrainingAtTime (#TrainingTime datetime2(0))
RETURNS INT
AS BEGIN
DECLARE #Trainees int;
SELECT #Trainees = COUNT(*)
FROM SampleTable
WHERE TrainingTime = #TrainingTime;
RETURN #Trainees;
END
GO
--Add the check constraint
ALTER TABLE SampleTable ADD CONSTRAINT MaxTrainees CHECK (dbo.TrainingAtTime(TrainingTime) <= 12) ;
GO
--Insert first trainee
INSERT INTO SampleTable
VALUES ('2018-04-26T06:00:00');
--It works
SELECT TrainingTime, COUNT(*) AS Trainees
FROM SampleTable
GROUP BY TrainingTime;
GO
--insert 11 more
INSERT INTO SampleTable
VALUES ('2018-04-26T06:00:00'),
('2018-04-26T06:00:00'),
('2018-04-26T06:00:00'),
('2018-04-26T06:00:00'),
('2018-04-26T06:00:00'),
('2018-04-26T06:00:00'),
('2018-04-26T06:00:00'),
('2018-04-26T06:00:00'),
('2018-04-26T06:00:00'),
('2018-04-26T06:00:00'),
('2018-04-26T06:00:00');
--It works
SELECT TrainingTime, COUNT(*) AS Trainees
FROM SampleTable
GROUP BY TrainingTime;
GO
--Try to insert another
INSERT INTO SampleTable
VALUES ('2018-04-26T06:00:00');
--It fails
SELECT TrainingTime, COUNT(*) AS Trainees
FROM SampleTable
GROUP BY TrainingTime;
GO
--Use a different time
INSERT INTO SampleTable
VALUES ('2018-04-26T08:00:00');
--it works
SELECT TrainingTime, COUNT(*) AS Trainees
FROM SampleTable
GROUP BY TrainingTime;
GO
--Clean up
DROP TABLE SampleTable;
DROP FUNCTION TrainingAtTime;
GO
If this isn't what you're after, unfortunately I don't understand your requirements due the the language barrier (and absence of a question).
I have to do this in SQL Server. Assume that I have 2 tables.
Based on parameters Name and Surname, I have to take PhysicianID from Table1.
After that I have to create new record using insert into stored procedure.
Something like this
CREATE PROCEDURE FIND_PHYSICIANID
#FirstName varchar(50),
#LastName varchar(50)
AS
BEGIN
DECLARE #PhysicianID int
SELECT #PhysicianID = PhysicianID
FROM Table1
WHERE FirstName = #FirstName AND LastName = #LastName
RETURN #PhysicianID
END
EXECUTE FIND_PHYSICIANID 'Kathlin','Jones'
CREATE PROCEDURE ADD_APPOINTMENT -- Create a new appointment
#AppointmentType VARCHAR(70), --Type of new appointment
#pAppointmentDate DATE, -- Date of new appointment
#aPhysicianID INT, --PhysicianID of requested physician (in this case during execution we will take value which we know-read from table for requested first and last name)
#apPatientID INT, --PatientID of chosen patient(let's say any from 1 to 14)
#aScheduleID INT, --ScheduleID, but here we have to take some ScheduleID for chosen PhysicianID (in this case during execution we will take value which we know-based on PHYSICIANID we may read value from table SCHEDULE)
#Status CHAR(1) -- Just Y or N
AS -- This "AS" is required by the syntax of stored procedures.
BEGIN -- Insert the new appointment
INSERT INTO [APPOINTMENT]([AppointmentType], [AppointmentDate],[aPhysicianID],
[apPatientID], [aScheduleID], [Status-Canceled])
VALUES (#AppointmentType, #pAppointmentDate, #aPhysicianID,
#apPatientID, #aScheduleID, #Status);
END;
EXECUTE ADD_APPOINTMENT 'Vaccinations', '2017-0831', '#PhysicianID', '12', '289', 'N'
You can get return id like this.
DECLARE #PhysicianID int
EXECUTE #PhysicianID = FIND_PHYSICIANID 'Kathlin','Jones'
you can use this param like this
EXECUTE ADD_APPOINTMENT 'Vaccinations','2017-0831', #PhysicianID, '12','289','N'
Presuming that the ability to find a physician is a common operation you could convert the FIND_PHYSICIANID stored procedure to a function and delay the lookup to within the consuming stored procedure that performs the operation.
create function [dbo].[FIND_PHYSICIANID]
(
#FirstName varchar(50),
#LastName varchar(50)
)
returns int
as
begin
declare #PhysicianId int
select #PhysicianID = PhysicianID
from dbo.Table1
where FirstName = #FirstName
and LastName = #LastName
return #PhysicianId
end
This will still keep the logic of finding a physician centralised but allow you to perform other actions and possibly validation if the only information you have available to you is the full name. Yes, it is more parameters but this is assuming the required parameters for the stored procedures are a manageable amount.
create procedure [dbo].[ADD_APPOINTMENT] -- Create a new appointment
#AppointmentType VARCHAR(70), --Type of new appointment
#pAppointmentDate DATE, -- Date of new appointment
#PhysicianFirstName varchar(50), -- // The first name of the physician
#PhysicianLastName varchar(50), -- // The last name of the physician
#apPatientID INT, --PatientID of chosen patient(let's say any from 1 to 14)
#aScheduleID INT, --ScheduleID, but here we have to take some ScheduleID for chosen PhysicianID (in this case during execution we will take value which we know-based on PHYSICIANID we may read value from table SCHEDULE)
#Status CHAR(1) -- Just Y or N
AS -- This "AS" is required by the syntax of stored procedures.
BEGIN -- Insert the new appointment
declare #aPhysicianID int
select #aPhysicianID = [dbo].[FIND_PHYSICIANID](#PhysicianFirstName, #PhysicianLastName varchar(50))
INSERT INTO [APPOINTMENT]([AppointmentType], [AppointmentDate],[aPhysicianID],
[apPatientID], [aScheduleID], [Status-Canceled])
VALUES (#AppointmentType, #pAppointmentDate, #aPhysicianID,
#apPatientID, #aScheduleID, #Status);
END
Alternatively, if it is desired to be separated and keep the existing stored procedure parameter signature then the previous answer that has the caller lookup the physician id via the stored procedure locally and then pass that parameter into the add appointment stored procedure should suffice your requirements.
As per the below pseudocode
Declare a variable for #physicianid of type int
Assign the #physicianid variable to the output of the FIND_PHYSICIANID stored procedure
Execute ADD_APPOINTMENT stored procedure with #physicianid variable as an input
I'm looking for suggestions on how to go about doing something that I am fairly certain that I should be able to do with SSIS.
I have two databases and I am updating Table B from Table A but as I do this I want to with ever successful write to Table B write some additional information to a log table back in the originating database. (See Illustration)
I'm not sure what control(s) I would use to accomplish this but suspect that it can be done inside of SSIS.
Use an OLEDB Transformation to do the UPDATE to table B, and then follow that with a Destination that writes to the log table.
After suggestions by Ivan Starostin and others on the board, I've opt'd to abandon using SSIS for doing this process and use stored procedures called from the code behind in the web page to perform this functionality. I'm including example of the insert process SP below as I'm working on the remainder but would like to close this question. Thanks to Ivan and all for your input. SSIS simply wasn't the best tool for this situation. It was much cleaner using SP as I found out.
USE [CInTracDB]
GO
/******** Object: StoredProcedure [dbo].[usp_InsertNewAssets] Script Date: 12/15/2016 3:00:00 PM *****/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Ken Carter>
-- Create date: <Dec 15, 2016>
-- Description: <Input Fields from Updates table, Insert all NEW records into CMDB.dbo.cmdb_assets, then copy record from
-- Updates to CInTracDB.dbo.Update_log, then Delete Record from Updates,
-- Return only sucesss / fail signal.
-- =============================================
CREATE PROCEDURE [dbo].[usp_InsertNewAssets](
#CAssetID as bigint,
#SubmitBy as varchar(50),
#SubmitDT as datetime,
#ApproveBy as varchar(50),
#Approved as char(10),
#ApprovedDT as datetime,
#Imported as char(10),
#ImportDT as datetime,
#AssetID as bigint,
#AssetType as int,
#AssetName as varchar(128),
#AssetShortDesc as varchar(50),
#AssetLongDesc as varchar(200),
#AssetAddNotes as varchar(254),
#AssetManuf as varchar(50),
#AssetModel as varchar(50),
#AssetTag as varchar(20),
#AssetAcqDate as datetime,
#AssetDTAssetID as varchar(20),
#AssetLocGrp as varchar(10),
#AssetLoc1 as varchar(8),
#AssetLoc2 as varchar(8),
#AssetLoc3 as varchar(8),
#AssetParent as bigint,
#AssetStatus as int,
#AssetPropType as int,
#AssetPrimUser as varchar(20),
#AssetEntered as datetime,
#AssetEnteredBy as varchar(50),
#AssetOwner as varchar(50),
#AssetCompany as varchar(10),
#AssetPriIPAddr as varchar(15),
#AssetPriMACAddr as varchar(17),
#AssetPriOS as varchar(20),
#AssetPriOSSP as varchar(20),
#AssetNotes as varchar(500),
#AssetAdminGrp as varchar(100),
#AssetSerialNum as varchar(75),
#AssetOperType as int,
#AssetOperStatus as int
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #AssetFACL as bit = 0
DECLARE #AssetStatVer as bit = 0
BEGIN
INSERT INTO CMDB.dbo.cmdb_assets (AssetType, AssetName, AssetShortDesc, AssetLongDesc, AssetAddNotes, AssetManuf,
AssetModel, AssetTag, AssetAcqDate, AssetDTAssetID, AssetLocGrp, AssetLoc1, AssetLoc2, AssetLoc3, AssetParent,
AssetStatus, AssetPropType, AssetPrimUser, AssetEntered, AssetEnteredBy, AssetOwner, AssetCompany, AssetPriIPAddr,
AssetPriMACAddr, AssetPriOS, AssetPriOSSP, AssetNotes, AssetAdminGrp, AssetSerialNum, AssetOperType,
AssetOperStatus, AssetFACL, AssetStatVer)
SELECT AssetType, AssetName, AssetShortDesc, AssetLongDesc, AssetAddNotes, AssetManuf, AssetModel, AssetTag,
AssetAcqDate, AssetDTAssetID, AssetLocGrp, AssetLoc1, AssetLoc2, AssetLoc3, AssetParent, AssetStatus, AssetPropType,
AssetPrimUser, AssetEntered, AssetEnteredBy, AssetOwner, AssetCompany, AssetPriIPAddr, AssetPriMACAddr, AssetPriOS,
AssetPriOSSP, AssetNotes, AssetAdminGrp, AssetSerialNum, AssetOperType, AssetOperStatus
FROM Updates
WHERE AssetID > 0
END
BEGIN
Insert INTO Update_log (CAssetID, SubmitBy, SubmitDT, ApproveBy, Approved, ApprovedDT, Imported, ImportDT, AssetID,
AssetType, AssetName, AssetShortDesc, AssetLongDesc, AssetAddNotes, AssetManuf, AssetModel, AssetTag, AssetAcqDate,
AssetDTAssetID, AssetLocGrp, AssetLoc1, AssetLoc2, AssetLoc3, AssetParent, AssetStatus, AssetPropType,
AssetPrimUser, AssetEntered, AssetEnteredBy, AssetOwner, AssetCompany, AssetPriIPAddr, AssetPriMACAddr, AssetPriOS,
AssetPriOSSP, AssetNotes, AssetAdminGrp, AssetSerialNum, AssetOperType, AssetOperStatus)
SELECT AssetType, AssetName, AssetShortDesc, AssetLongDesc, AssetAddNotes, AssetManuf, AssetModel, AssetTag,
AssetAcqDate, AssetDTAssetID, AssetLocGrp, AssetLoc1, AssetLoc2, AssetLoc3, AssetParent, AssetStatus, AssetPropType,
AssetPrimUser, AssetEntered, AssetEnteredBy, AssetOwner, AssetCompany, AssetPriIPAddr, AssetPriMACAddr, AssetPriOS,
AssetPriOSSP, AssetNotes, AssetAdminGrp, AssetSerialNum, AssetOperType, AssetOperStatus
FROM Updates
WHERE AssetID > 0
END
BEGIN
DELETE FROM Updates
WHERE (AssetID > 0)
END
END
GO
I'm getting this error when accessing a stored procedure in SQL Server:
Procedure or function 'resetdata' expects parameter '#FirstName', which was not supplied.
This is my table:
CREATE TABLE dbo.Client
(
ClientID int IDENTITY(1,1) PRIMARY KEY NOT NULL,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
StreetAddress VARCHAR(50) NULL,
Suburb VARCHAR(15)NULL,
C_State VARCHAR(3) NULL, --CHECK (C_State IN ('QLD', 'NSW', 'VIC', 'TAS', 'SA', 'WA', 'NT', 'ACT')),
PostCode SMALLINT NOT NULL,
PhoneNumber VARCHAR(11) NULL,
);
GO
ALTER TABLE Client
ADD CONSTRAINT state_ CHECK (C_State IN ('QLD', 'NSW', 'VIC', 'TAS', 'SA', 'WA', 'NT', 'ACT')),
CONSTRAINT check_post_code CHECK ([PostCode] LIKE '[0-9][0-9][0-9][0-9]' or [PostCode] LIKE '[0-9][0-9][0-9]');
GO
This is my stored procedure:
CREATE PROCEDURE [dbo].[resetdata]
#FirstName varchar(50),
#LastName varchar(50),
#PostCode smallint
AS
BEGIN
INSERT INTO A1.dbo.Client (FirstName, LastName, PostCode)
VALUES(#FirstName, #LastName, #PostCode)
END;
GO
EXEC dbo.resetdata;
INSERT INTO Client(FirstName, LastName, PostCode)
VALUES ('F', 'L', 12345);
Error message means exactly what it says: your SP is expecting three arguments as declared.
This is your SP header definition:
create procedure [dbo].[resetdata]
#FirstName varchar(50),
#LastName varchar(50),
#PostCode smallint
Three arguments. None of them has default.
This is how you're attempting to execute it:
EXEC dbo.resetdata;
No arguments provided. This causes the error from your question. Pass arguments to avoid error message.
Couple of things:
if you will try to apply script of your SP to test database or another copy of your database, you will have to modify your first line with USE A1. I'd suggest to remove this line. Choose DB once you connect, then just run all scripts on current database
Insert INTO A1.dbo.Client - same note about different databases and one more - if you already defined database with USE A1 at the beginning of the script, why are you referring same DB explicitly? If your SP and table are supposed to be in same DB - don't specify DB.
There are a couple of issues here:
The EXEC procedure is not passing the parameters required.
There is a constraint on the Postcode that will fail with 12345.
The correct code to run your stored procedure would be:
EXEC [dbo].[resetdata]
#FirstName = 'F',
#LastName = 'L',
#PostCode = 123
Try this:
USE A1;
GO
create procedure [dbo].[resetdata]
#FirstName varchar(50),
#LastName varchar(50),
#PostCode smallint
AS
BEGIN
Insert INTO A1.dbo.Client (FirstName,LastName,PostCode)
VALUES(#FirstName,#LastName,#PostCode)
END;
GO
EXEC dbo.resetdata #FirstName='F', #LastName='L', #PostCode=12345
--INSERT INTO Client(FirstName,LastName,PostCode) VALUES ('F','L',12345); No need to this Insert
Note: In sample data, you are going to insert 12345 to PostCode column, So it seems that 5 digit numbers are valid, but you have check constraint that shows PostCode should be 3 or 4 digit length. If 5 digit is valid so pay attention to the PostCode column's data type as it's maximum value is 32767. So if you want to insert a record with PostCode greater than this value you will get an error. May be it would be better to define it as INT and control it's value via a Check Constraint and also change the current check constraint definition on this column.