while loop to get two variables to stored procedure - sql

I want to write a stored procedure to loop through the table which has membership id and person id details and pass it as variable to stored procedure.
Any thoughts on how to do it. Any help is highly appreciated.
DECLARE #membership NUMERIC(9)
DECLARE #person_id NUMERIC(9)
DECLARE #id_num INT
WHILE (
set #id_num=id_num+1
SELECT membership_id,person_id FROM [dbo].[reb] WHERE id_num <1160
EXEC p_get_details #membership_id, person_id

You have two options. first one is to pass two parameters to procedure p_get_details , each parameter being a comma separated string containing concatenated values of membership_id and person_id columns.
Other is to pass the whole resultset from SELECT query as a Table Valued Parameter to the procedure.

If you need to call the proc again and again for different table values then u can create a temp table which has all the membership and personids
See If this code works for you:-
DECLARE #membership_id NUMERIC(9)
DECLARE #person_id NUMERIC(9)
if(OBJECT_ID('tempdb..#tempids') is not null)
drop table #tempids
SELECT membership_id,person_id
into #tempids
FROM [dbo].[reb]
WHERE id_num <1160
while exists(select 1 from #tempids)
begin
-- select 1 row which will be called by proc
select top 1 #membership_id=membership_id
#person_id =person_id
from #tempids
EXEC p_get_details #membership_id, #person_id
--delete the ids which have been called by proc
delete from #tempids
where
membership_id=#membership_id
person_id =#person_id
end

Related

Return AutoIncremeting ID upon insert

I have a stored procedure that inserts into a table that has two values, id and username. The id field is autoincremeting so my stored procedure looks like:
CREATE PROCEDURE [dbo].[sp_test]
#username varchar(50)
AS
BEGIN
INSERT INTO dbo.testtable(username)
SELECT
#username
FROM
tbl.test2
WHERE
username IS NOT NULL
How can I return the id even when there it is not explicitly stated? I attempted the SCOPE_IDENTITY(); keyword but I was receiving blanks and nulls.
Taking a guess as to what you want I think it would be something more like this.
CREATE PROCEDURE [dbo].[Insert_test]
(
#username varchar(50)
) AS
BEGIN
INSERT INTO dbo.testtable
(
username
)
VALUES
(
#username
)
select SCOPE_IDENTITY()
END
If you're really inserting several rows from a table, you can get the ids this way:
INSERT INTO dbo.testtable(username)
output inserted.id
SELECT username
FROM dbo.test2
where username is not null

store result of select query into array variable

I want to store the result of this sql query in variable #a. The result contains 17 rows. How to edit this code in order to store the rows in #a?
declare #a uniqueidentifier
select EnrollmentID into #a from Enrollment
You cannot store 17 values inside a scalar variable. You can use a table variable instead.
This is how you can declare it:
DECLARE #a TABLE (id uniqueidentifier)
and how you can populate it with values from Enrollment table:
INSERT INTO #a
SELECT EnrollmentID FROM Enrollment
You should declare #a as a Table Variable with one column of type unique identifier as follows:
DECLARE #a TABLE (uniqueId uniqueidentifier);
INSERT INTO #a
SELECT EnrollmentID
FROM Enrollment;

SQL Server : split column into table in a trigger

I have a table that looks something like this:
UserID Email
-----------------------------------
1 1_0#email.com;1_1#email.com
2 2_0#email.com;2_1#email.com
3 3_0#email.com;3_3#email.com
And I need to create a temp table that will look like this:
UserID Email
-----------------------------------
1 1_0#email.com
1 1_1#email.com
2 2_0#email.com
2 2_1#email.com
3 3_0#email.com
3 3_1#email.com
The temp table will be used in a update trigger and I was wondering if there is a more elegant approach than doing something like this:
-- Create temp table to hold the result table
CREATE TABLE #resultTable(
UserID int,
Email nvarchar(50)
)
-- Create temp table to help iterate through table
CREATE TABLE #tempTable(
ID int IDENTITY(1,1),
UserID int,
Email nvarchar(50)
)
-- Insert data from updated table into temp table
INSERT INTO #tempTable
SELECT [UserId], [Email]
FROM inserted
-- Iterate through temp table
DECLARE #count int = ##ROWCOUNT
DECLARE #index int = 1
WHILE (#index <= #count)
BEGIN
DECLARE #userID int
DECLARE #email nvarchar(50)
-- Get the user ID and email values
SELECT
#userID = [UserID], #email = [Email]
FROM #tempTable
WHERE [ID] = #index
-- Insert the parsed email address into the result table
INSERT INTO #resultTable([UserID], [Email])
SELECT #userID, [Data]
FROM myFunctionThatSplitsAColumnIntoATable(#email, ';')
SET #index = #index + 1
END
-- Do stuff with the result table
You'd better avoid iterative approaches when using T-SQL unless strictly necessary, specially inside triggers.
You can use the APPLY operator.
From MSDN:
The APPLY operator allows you to invoke a table-valued function for each row returned by an outer table expression of a query.
So, you can try to replace all your code with this:
INSERT INTO #resultTable(UserID, Email)
SELECT T1.UserID
,T2.Data
FROM updated T1
CROSS APPLY myFunctionThatSplitsAColumnIntoATable(T1.Email, ';') AS T2

Insert another parameter along with table type

The table tblEffort has 3 columns EmployeeName, Effort, Date. I get the first 2 column values from a table type parameter and have to insert a common date for all these values.
do not have the option to include timesheetdate in dtCSV
There should be some other way than running an update again on the inserted columns right?
The below code gives the error - Must declare the table variable "#TimesheetDate"
CREATE TYPE dbo.SaveEffort_TableType AS TABLE
(
EmployeeName varchar(200),
Effort decimal(18,2)
);
GO
CREATE PROCEDURE SaveEmployeeEffort
(
#TimesheetDate datetime,
#dtCSV AS dbo.SaveEffort_TableType readonly
)
AS
BEGIN
INSERT INTO tblEffort(EmployeeName,Effort,[Date])
SELECT * FROM #dtCSV,#TimesheetDate
END
You need to put the variable into the SELECT clause, not the FROM clause
CREATE PROCEDURE SaveEmployeeEffort
(
#TimesheetDate datetime,
#dtCSV AS dbo.SaveEffort_TableType readonly
)
AS
BEGIN
INSERT INTO tblEffort(EmployeeName,Effort,[Date])
SELECT EmployeeName,Effort, #TimesheetDate FROM #dtCSV
END

SQL Find and Insert

I have name of client and name of doctor. I want to get there ID from DB and insert IDs into table.
CREATE PROCEDURE AddMedicalCard
#Client nchar,
#Doctor nchar
AS
BEGIN
SELECT Clients.[ClientCode] AS [Code]
Into #NewClientCode
FROM Clients
WHERE Clients.[ClientName]=#Client
SELECT Personal.[DoctorCode] AS [Code]
Into #NewDoctorCode
FROM Personal
WHERE Personal.[DoctorName]=#Doctor
INSERT INTO MedicalCard
VALUES (#NewClientCode.[Code].First, #NewDoctorCode.[Code].First)
DROP TABLE #NewClientCode
DROP TABLE #NewDoctorCode
END
GO
Errors:
The multi-part identifier "#NewDoctorCode.Code.First" could not be bound.
The multi-part identifier "#NewClientCode.Code.First" could not be bound.
Column name or number of supplied values does not match table definition.
MedicalCard table design:
RecordingCode(Key), ClientCode, DoctorCode
and 5 other nullable columns.
Error message says it all. There is no such thing as #NewDoctorCode.Code.First. Your job can be easily & cleanly done as follows.
Note: It is not very correct to get clientcode and doctorcode by their names as there could be more than 1 client & doctors with the same name.
--declare two variables
declare #clientCode varchar(50), #doctorCode varchar(50)
--assign clientCode
SELECT TOP 1 #clientCode = Clients.[ClientCode]
FROM Clients
WHERE Clients.[ClientName]=#Client
--assign doctorCode
SELECT TOP 1 #doctorCode = Personal.[DoctorCode]
FROM Personal
WHERE Personal.[DoctorName]=#Doctor
--finally insert them to MedicalCard table
INSERT INTO MedicalCard (clientCodeColumn,doctorCodeColumn) --Column Names
VALUES (#clientCode,#doctorCode)
Do something like this
DECLARE #i INT;
SELECT #i = id FROM youtable;
BEGIN
Insert into tablename(column1) values(#i)
END
Try this, you should use variables and not table. If you use table then you should use insert into table select col
DECLARE #NewClientCode int
DECLARE #NewDoctorCode int
SELECT #NewClientCode = Clients.[ClientCode]
FROM Clients
WHERE Clients.[ClientName]=#Client
SELECT #NewDoctorCode = Personal.[DoctorCode]
FROM Personal
WHERE Personal.[DoctorName]=#Doctor
INSERT INTO MedicalCard
VALUES (#NewClientCode, #NewDoctorCode)
Try to use this SP:
CREATE PROCEDURE AddMedicalCard
#Client nchar,
#Doctor nchar
AS
BEGIN
INSERT INTO MedicalCard
VALUES (
SELECT TOP 1 Clients.[ClientCode]
FROM Clients
WHERE Clients.[ClientName]=#Client,
SELECT TOP 1 Personal.[DoctorCode]
FROM Personal
WHERE Personal.[DoctorName]=#Doctor
)
END
GO