within a sql while loop, get id of last inserted row then insert it into a different table, using OUTPUT? - sql

I am writing some sql, using sql server 2008, to loop around some records. Within this loop I need to insert a row and the ID of that row will be put into a field in an existing record in a different table. I thought I would be able to achieve this with OUTPUT but I couldn't find an example of exactly what I wanted to do.
Here's what I have so far:
DECLARE #courseTempID INT
DECLARE #courseID INT
DECLARE #academicYearID INT
DECLARE #courseCode VARCHAR(10)
DECLARE #uio_id INT
DECLARE #creatorIntranetUserID INT
WHILE (SELECT count(*) FROM CoursesTemp WHERE dmprocessed = 0) > 0
BEGIN
SELECT TOP 1 #id = courseTempID FROM CoursesTemp WHERE dmprocessed = 0
SELECT TOP 1 #academicYearID = academicYearID FROM CoursesTemp WHERE dmprocessed = 0
SELECT TOP 1 #courseCode = courseCode FROM CoursesTemp WHERE dmprocessed = 0
SELECT TOP 1 #uio_id = uio_id FROM CoursesTemp WHERE dmprocessed = 0
SELECT TOP 1 #creatorIntranetUserID = creatorIntranetUserID FROM CoursesTemp WHERE dmprocessed = 0
INSERT INTO dbo.Courses VALUES(3,#academicYearID,1,#courseCode,#uio_id,GETDATE(),#creatorIntranetUserID)
OUTPUT INSERTED.courseID INTO #courseID
UPDATE CoursesTemp SET dmprocessed = 1, courseID = #courseID WHERE courseTempID = #courseTempID
END
The error I am getting is "Incorrect syntax near 'INSERTED'".
Can anyone help me work out how to use OUTPUT in this way please?

A few performance improvements applied. It is safer to use SCOPE_IDENTITY()
DECLARE #courseTempID INT
DECLARE #courseID INT
DECLARE #academicYearID INT
DECLARE #courseCode VARCHAR(10)
DECLARE #uio_id INT
DECLARE #creatorIntranetUserID INT
DECLARE #id INT
WHILE EXISTS(SELECT 1 FROM CoursesTemp WHERE dmprocessed = 0)
BEGIN
SELECT TOP 1 #id = courseTempID
,#academicYearID = academicYearID
,#courseCode = courseCode
,#uio_id = uio_id
,#creatorIntranetUserID = creatorIntranetUserID
FROM CoursesTemp WHERE dmprocessed = 0
INSERT INTO dbo.Courses VALUES(3,#academicYearID,1,#courseCode,#uio_id,GETDATE(),#creatorIntranetUserID)
UPDATE CoursesTemp SET dmprocessed = 1, courseID = SCOPE_IDENTITY() WHERE courseTempID = #courseTempID
END

OUTPUT needs to go between INSERT INTO dbo.Courses and VALUES(...)
You also have OUTPUT INSERTED.courseID INTO #CourseId but #CourseId is an int variable, it needs to be the table you want to insert into.
EDIT I've reread what you're tying to do. Instead of using OUTPUT, you can change your last line to
UPDATE CoursesTemp SET dmprocessed = 1, courseId = SCOPE_IDENTITY()
WHERE courseTempID = #courseTempID

You may be able to use ##IDENTITY to retrieve the last-inserted ID value. http://msdn.microsoft.com/en-us/library/ms187342.aspx

Related

SQL - slow While loop

I have the following T-SQL code that is either adding or updating 1 record at a time to a temp table. Does anyone have any suggestions to speed this process up?
DECLARE #Total AS INT
SELECT #Total = count(AgentsID) from #TempAgentsConcat
DECLARE #counter AS INT
SET #counter = 1
DECLARE #CurrentVal AS NVARCHAR(1024)
DECLARE #RowCount AS INT
DECLARE #OBJ_ID AS INT
while (#counter <= #Total)
begin
SELECT #OBJ_ID = Id FROM #TempAgentsConcat WHERE AgentsId = #counter
SELECT #CurrentVal = SVRMachine FROM #TempAgentsConcat WHERE ID = #OBJ_ID
IF EXISTS (SELECT * FROM #TempEndpoints WHERE ID = #OBJ_ID)
BEGIN
UPDATE #TempEndpoints SET SVRMachine = #CurrentVal WHERE ID = #OBJ_ID
END
ELSE
BEGIN
INSERT INTO #TempEndpoints (SVRMachine, IPPort, ID)
VALUES (#CurrentVal, NULL, #OBJ_ID)
END
--END
SET #counter = #counter + 1
end
It looks like, you are trying to merge one table into other. First lets talk of couple of issues in your query-
1. Avoid using loops unless it's extremely necessary.
2. You are assigning two different variables by reading same row in 2 queries.
You can do this in single query like
SELECT #OBJ_ID = Id,#CurrentVal = SVRMachine FROM #TempAgentsConcat WHERE AgentsId = #counter
instead of 2 queries
SELECT #OBJ_ID = Id FROM #TempAgentsConcat WHERE AgentsId = #counter
SELECT #CurrentVal = SVRMachine FROM #TempAgentsConcat WHERE ID = #OBJ_ID
Let's rewrite the query without using loops. The answer by #Cetin is one of the solutions. Your requirement looks classic example of merging tables, so you may use SQL MERGE (SQL server 2008 and above). You can read more about MERGE, here, checkout the example 'C'.
Using MERGE, your query will look like below.
MERGE INTO #TempEndpoints AS Target
USING (SELECT SVRMachine , Id from #TempAgentsConcat)
AS Source (SVRMachine, ID)
ON Target.ID = Source.ID
WHEN MATCHED THEN
UPDATE SET SVRMachine = Source.SVRMachine
WHEN NOT MATCHED BY TARGET THEN
INSERT (ID, IPPort, SVRMachine) VALUES (Id, NULL,SVRMachine)
Why would you use a lot of variables and loop. SQL server (any SQL series database as well) works best with sets, rather than loops:
UPDATE #TempEndpoints
SET SVRMachine = ac.SVRMachine
FROM #TempAgentsConcat ac
WHERE #TempEndpoints.Id = ac.ID;
INSERT INTO #TempEndpoints
(
SVRMachine,
ID
)
SELECT SVRMachine,
ID
FROM #TempAgentsConcat ac
WHERE NOT EXISTS
(
SELECT * FROM #TempEndpoints ep WHERE ep.ID = ac.ID
);

SQL Server: is this a bug or do I have a misunderstanding?

Today I'm found a very sticky problem on SQL Server 2014.
Scenario: I want to pay awards to my customer (some pin code for cell phone operator)
In last cycle of loop T.Used = 0 condition is bypassed and is not working. I know in other conditions in that query (T.Cash < (#myAwards - #paid)) is there a mistake and I must to use T.Cash <= (#myAwards - #paid) instead of this but please focus on main question.
Why it's happened when I update Used flag to 1 (True) then in next loop it's selected while it doesn't have a valid condition (T.Used = 0)?
DECLARE #myAwards INT = 90000,
#paid INT = 0;
DECLARE #Temp TABLE
(
Id INT NOT NULL,
Pin VARCHAR(100) NOT NULL,
Cash INT NOT NULL,
[Weight] INT NULL,
Used BIT NOT NULL
)
INSERT INTO #Temp
SELECT
UPFI.Id, UPFI.PinCode,
PT.Cash, NULL, 0
FROM
dbo.UploadedPinFactorItem UPFI WITH (NOLOCK)
INNER JOIN
dbo.PinType PT WITH (NOLOCK) ON PT.ID = UPFI.PinTypeID
WHERE
PT.Cash <= #myAwards
UPDATE T
SET [Weight] = ISNULL((SELECT COUNT(TT.Id)
FROM #Temp TT
WHERE TT.Cash = T.Cash), 0) * T.Cash
FROM #Temp T
--For debug (first picture)
SELECT * FROM #Temp
DECLARE #i int = 1
DECLARE #count int = 0
SELECT #count = COUNT([Id]) FROM #Temp C WHERE C.Used = 0
WHILE (#i <= #count AND #paid < #myAwards)
BEGIN
DECLARE #nextId INT,
#nextCash INT,
#nextFlag BIT;
-- 'T.Used = 0' condition is by passed
SELECT TOP (1)
#nextId = T.Id, #nextCash = T.Cash, #nextFlag = T.Used
FROM
#Temp T
WHERE
T.Used = 0
AND T.Cash < (#myAwards - #paid)
ORDER BY
T.[Weight] DESC, T.Cash DESC, T.Id DESC
UPDATE #Temp
SET Used = 1
WHERE Id = #nextId
SET #i = #i + 1
SET #paid = #paid + #nextCash
--Show result in second picture
SELECT
#i AS 'i', #paid AS 'paid', #nextFlag AS 'flag', #nextId AS 'marked Id',*
FROM
#temp T
ORDER BY
T.[Weight] DESC, T.Cash DESC, T.Id DESC
END
SELECT 'final', #paid, *
FROM #temp T
ORDER BY T.[Weight] DESC, T.Cash DESC, T.Id DESC
Please let me to understand this is a bug or I have misunderstanding
First screenshot:
Second screenshot (result of loop):
Third screenshot (final result):
As per my comments:
This isn't a problem with the condition, the problem is with the implemented logic. After i = 4, there are no more rows where T.Used = 0 AND T.Cash < (#myAwards - #paid), that makes it so your reassigning variables gets zero rows, so they mantain the previous values.
You can test this behavior by doing:
DECLARE #A INT = 10;
SELECT #A = object_id
FROM sys.all_objects
WHERE name = 'an object that doesn''t exist'
SELECT #A;

Looking for missing gaps for getting "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS."

I have the following query to find missing gaps in the sort for each ModelID but I keep getting the following error and don't know why.
What I'm doing is in my first loop I am looping through the modelID's and in the inner loop I am looking for the missing gaps in the siSort column for that modelID and putting that into a temp table.
Msg 116, Level 16, State 1, Line 27
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
USE crm
GO
BEGIN
DECLARE #ID INT
DECLARE #MAXID INT
DECLARE #COUNT INT
DECLARE #iCustomListModelID INT
DECLARE #iCustomFieldID INT
DECLARE #MissingIds TABLE (ID INT)
DECLARE #Output TABLE (iCustomListModelID INT, siSort INT, iListItemID INT)
-- SELECT ALL DISTINCT ICustomListModelID's FROM CustomList Table
SELECT DISTINCT cl.iCustomListModelID
INTO #DistinctModelIDs
FROM dbo.CustomListModel clm
INNER JOIN dbo.CustomListType clt ON clm.iCustomListTypeID = clt.iCustomListTypeID
AND clt.vchCustomListTypeDescription = N'Household Custom Field'
INNER JOIN dbo.CustomList cl ON clm.iCustomListModelID = cl.iCustomListModelID
INNER JOIN dbo.CustomField cf ON cl.iListItemID = cf.iCustomFieldID
ORDER BY cl.iCustomListModelID
-- Get iCustomFieldID to insert into iListItemID
SET #iCustomFieldID = (SELECT * FROM dbo.CustomField cf WHERE vchLabel = '')
-- Begin Outer loop to go through each iCustomListModelID
WHILE (SELECT COUNT(iCustomListModelID) AS Total FROM #DistinctModelIDs) > 0
BEGIN
-- GRAB THE NEXT iCustomListModelID
SELECT #iCustomListModelID = (SELECT TOP 1 iCustomListModelID FROM #DistinctModelIDs);
DROP TABLE #List
SELECT siSort INTO #List FROM CustomList WHERE iCustomListModelID = #iCustomListModelID
SELECT #MAXID = siSort FROM dbo.CustomList WHERE iCustomListModelID = #iCustomListModelID
SET #ID = 1;
-- Inner loop to go through the missing gaps in siSort
WHILE #ID <= #MAXID
BEGIN
IF NOT EXISTS (
SELECT 'X' FROM #List WHERE siSort = #ID
)
INSERT INTO #MissingIDs (ID)
VALUES (#ID)
--INSERT THE MISSING ID INTO #outputTable Table
INSERT INTO #Output (iCustomListModelID, siSort, iListItemID)
VALUES (#iCustomListModelID, #ID, #iCustomFieldID)
SET #ID = #ID + 1;
END;
-- DELETE CURRENT iCustomListModelID
DELETE FROM #DistinctModelIDs WHERE iCustomListModelID = #iCustomListModelID
END
SELECT * FROM #Output
END;
One possibility is that the issue is this line:
SET #iCustomFieldID = (SELECT * FROM dbo.CustomField cf WHERE vchLabel = '')
If dbo.CustomerField doesn't have exactly one column (more than one column seems likely because vchLabel is already one column in the table), then this will generate an error of that type.

SQL Server generate script for views and how to decide order?

I am generating the script for views using SQL Server built-in feature (Task -> Generate script). I am creating separate file for each object (of view). I have say around 400 files (containing SQL script of all views) to be executed on another database and to do that automatically I have created BAT file which takes care of that.
There are views which are dependent on other views and due to that many views failed to execute. Is there any way by which we can set order of execution and get rid off the failure ?
Any pointers would be a great help.
Please let me know if you need more details.
Thanks
Jony
Could you try this query? You can execute the create scripts in order to "gen" (generation).
DECLARE #cnt int = 0, #index int;
DECLARE #viewNames table (number int, name varchar(max))
DECLARE #viewGen table (id uniqueidentifier, gen int, name varchar(max), parentId uniqueidentifier)
INSERT INTO #viewNames
SELECT ROW_NUMBER() OVER(ORDER BY object_Id), name FROM sys.views
SELECT #cnt = COUNT(*) FROM #viewNames
SET #index = #cnt;
WHILE ((SELECT COUNT(*) FROM #viewGen) < #cnt)
BEGIN
DECLARE #viewName varchar(200)
SELECT #viewName = name FROM #viewNames WHERE number = #index;
DECLARE #depCnt int = 0;
SELECT #depCnt = COUNT(*) FROM sys.dm_sql_referencing_entities ('dbo.' + #viewName, 'OBJECT')
IF (#depCnt = 0)
BEGIN
INSERT INTO #viewGen SELECT NEWID(), 0, name, null FROM #viewNames WHERE number = #index;
END
ELSE
BEGIN
IF EXISTS(SELECT * FROM sys.dm_sql_referencing_entities ('dbo.' + #viewName, 'OBJECT') AS r INNER JOIN #viewGen AS v ON r.referencing_entity_name = v.name)
BEGIN
DECLARE #parentId uniqueidentifier = NEWID();
INSERT INTO #viewGen SELECT #parentId, 0, name, null FROM #viewNames WHERE number = #index;
UPDATE v
SET v.gen = (v.gen + 1), parentId = #parentId
FROM #viewGen AS v
INNER JOIN sys.dm_sql_referencing_entities('dbo.' + #viewName, 'OBJECT') AS r ON r.referencing_entity_name = v.name
UPDATE #viewGen
SET gen = gen + 1
WHERE Id = parentId OR parentId IN (SELECT Id FROM #viewGen WHERE parentId = parentId)
END
END
SET #index = #index - 1
IF (#index < 0) BEGIN SET #index = #cnt; END
END
SELECT gen as [order], name FROM #viewGen ORDER BY gen
Expecting result:
order name
0 vw_Ancient
1 vw_Child1
1 vw_Child2
2 vw_GrandChild

SQL insert statement for each update row

Now i made cursor to update in 2 tables and insert in one table based on specific select statement this select statement return 2 columns x , y i need x to update in table "PX" because x is Primary key in this table and need x to update in table "FX" because x is foreign key in this table then insert in third table x data.
I need to change this cursor and use update and insert script i tried but i found that i need to make loop to achieve my target so if any one know if i can change this cursor .
And thanks in advance
DECLARE #id int
DECLARE #clientid uniqueidentifier
DECLARE #code int
DECLARE #Wtime int
DECLARE #closeComplaint CURSOR
SET #closeComplaint = CURSOR FAST_FORWARD
FOR
SELECT ComplaintId, [ClientId]
FROM complaint
WHERE ComplaintStatusId = 5
AND (waitingForCutomerCloseDateTime < GETDATE() OR
waitingForCutomerCloseDateTime = GETDATE())
OPEN #closeComplaint
FETCH NEXT FROM #closeComplaint INTO #id, #clientid
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT
waitingForCutomerCloseTime = #Wtime
FROM
SystemConfiguration
WHERE
ClientId = #clientid
SELECT
[Code] = #code
FROM
[dbo].[resp_users]
WHERE
ClientId = #clientid
UPDATE activity
SET ActivityStatus = 4,
CompletionDate = GETDATE(),
ClosedBy = #code
WHERE [ComplaintId] = #id
UPDATE [dbo].[Complaint]
SET ComplaintStatusId = 2
WHERE [ComplaintId] = #id
INSERT INTO [dbo].[Note] ([Note_Description], [ClientId], [User_Code], [Visible_Internal],
[ComplaintId], [Note_DateTime], [ComplainantId],
[OneStopDesk_CustomerEmail], [OneStopDesk_CustomerUsername], [Private])
VALUES (N'Automatically closed by system after ' + #Wtime, #clientid, #code, 1,
#id, GETDATE(), null, null, null, 1)
FETCH NEXT FROM #closeComplaint INTO #id, #clientid
END
CLOSE #closeComplaint
DEALLOCATE #closeComplaint
I'm not entirely sure I got everything right (you didn't post the table structures, so I can really only guess at times how those tables are connected) - but you should be able to basically do all of this in 3 simple, set-based statements - and that should be a LOT faster than the cursor!
-- declare table variable
DECLARE #Input TABLE (CompaintID INT, ClientID INT)
-- save the rows into a table variable
INSERT INTO #Input (ComplaintID, ClientID)
SELECT ComplaintID, ClientID
FROM dbo.Complaint
WHERE ComplaintStatusId = 5
AND waitingForCustomerCloseDateTime <= GETDATE()
UPDATE a
SET ActivityStatus = 4,
CompletionDate = GETDATE(),
ClosedBy = u.Code
FROM dbo.Activity a
INNER JOIN #Input i ON a.ComplaintId = i.ComplaintId
INNER JOIN dbo.resp_users u ON i.ClientId = u.ClientId
UPDATE dbo.Complaint
SET ComplaintStatusId = 2
WHERE
ComplaintStatusId = 5
AND waitingForCustomerCloseDateTime <= GETDATE()
INSERT INTO dbo.Note ([Note_Description], [ClientId], [User_Code], [Visible_Internal],
[ComplaintId], [Note_DateTime], [ComplainantId],
[OneStopDesk_CustomerEmail], [OneStopDesk_CustomerUsername], [Private])
SELECT
N'Automatically closed by system after ' + sc.waitingForCustomerCloseTime,
i.ClientId, u.Code, 1,
i.ComplaintId, GETDATE(), null, null, null, 1
FROM
#Input i
INNER JOIN
dbo.SystemConfiguration sc ON i.ClientId = sc.ClientId
INNER JOIN
dbo.resp_user u ON u.ClientId = i.ClientId