I am trying to select the second row in a column, I want to continue the loop if the next row is null. Here is my script:
DECLARE #MAXID INT, #Counter INT, #clientId AS int
SET #COUNTER = 2
SET #clientId = 11
SELECT #MAXID = COUNT(DISTINCT vw_masterView.LastVisitDate) FROM vw_MasterView where clientId = #clientId;
WHILE (#COUNTER <= #MAXID)
BEGIN
SELECT myData FROM
(
SELECT myData , ROW_NUMBER() OVER (order by vw_masterView.LastDate desc) AS Rownumber
FROM vw_MasterView where clientId = #clientId
) results
WHERE results.Rownumber = #COUNTER
IF Results.myData IS NOT NULL BREAK;
SET #COUNTER = #COUNTER + 1
END
I get the following error:
The multi-part identifier "Results.myData" could not be bound.
Thank you
There is no variable called Results in there. Set myData at variable and check null with the variable. Try this:
BEGIN
DECLARE #myData VARCHAR(20)
SELECT #myData = myData FROM
(
SELECT
myData,
ROW_NUMBER() OVER (order by vw_masterView.LastDate desc) AS Rownumber
FROM vw_MasterView where clientId = #clientId
) results
WHERE results.Rownumber = #COUNTER
IF #myData IS NOT NULL BREAK;
SET #COUNTER = #COUNTER + 1
END
Your use of the Results.myData is deeply flawed. You are not inside the query itself, so you can't reference a table and column. I believe this will accomplish what you are trying to do though.
DECLARE #clientId AS int = 11
SELECT
*
FROM (
SELECT myData , ROW_NUMBER() OVER (order by vw_masterView.LastDate desc) AS Rownumber
FROM vw_MasterView
where clientId = #clientId
and myData is not null
) a
WHERE Rownumber=2
Related
I have tried this code:
DECLARE #json_doc nvarchar(4000) = '{"Name1":"Value1", "Name2":"Value2"}';
SELECT
CASE WHEN (SELECT COUNT(*) FROM OPENJSON(#json_doc)) > 0
THEN JSON_VALUE(#json_doc,'$.' + (SELECT TOP(1) [key] FROM OPENJSON(#json_doc)))
ELSE NULL END
But it gives me this error:
Msg 13610 Level 16 State 1 Line 3
The argument 2 of the "JSON_VALUE or JSON_QUERY" must be a string literal.
Anyone know how to get this element?
I think you are looking for something like this:
DECLARE #json_doc nvarchar(4000) = '{"Name1":"Value1", "Name2":"Value2"}';
WITH CTE AS
(
SELECT [Value],
-- row number is ordered by the keys first appearence in the json source.
ROW_NUMBER() OVER(ORDER BY CHARINDEX('"' + [Key] +'":', #json_doc)) As rn
FROM OPENJSON(#Json_doc)
)
-- Get the value if json_doc contains any value
SELECT [Value] As ValueOrDefault
FROM CTE
WHERE rn = 1
UNION
-- Get null if not
SELECT NULL
WHERE NOT EXISTS (SELECT 1 FROM CTE);
The result of this query would be Value1 for that json.
However, if the #json_doc would be empty (set #json_doc = '{}';) it will return NULL.
DB<>Fiddle
This should work for you:
DECLARE #json_doc nvarchar(4000) = '{"Name1":"Value1", "Name2":"Value2"}';
DECLARE #sql nvarchar(max) = '
DECLARE #json_doc nvarchar(4000) = ''' + #json_doc + ''';
SELECT
CASE WHEN (SELECT COUNT(*) FROM OPENJSON(#json_doc)) > 0
THEN JSON_VALUE(#json_doc,''$.' + (SELECT TOP(1) [key] FROM OPENJSON(#json_doc)) + ''')
ELSE NULL END
';
EXECUTE (#sql);
I have this table with 22 rows as above
I am getting a converted table as above
I created following procedure in order to get result table
ALTER PROCEDURE [dbo].[proc_YS_BAB_IR_Item]
#UserId int
AS
BEGIN TRAN
DECLARE #SqlQry NVARCHAR(MAX);
SET #SqlQry = N''
DECLARE #Cnt INT = 1, #EndCnt INT = 25,
#v_UserId INT = CAST(#UserId AS VARCHAR(MAX));
CREATE TABLE #TempColumns
(
Calculate_ItemIdentifier VARCHAR(MAX),
SeqOrder INT
)
WHILE #cnt <= #EndCnt
BEGIN
INSERT INTO #TempColumns
SELECT
'IR'+ CAST(#Cnt AS VARCHAR(MAX)),
#Cnt
SET #Cnt = #Cnt + 1;
END
DECLARE #DATA VARCHAR(10), #DATA1 VARCHAR(10) = '000000'
DECLARE #zero_str VARCHAR(6) = '000000'
-- Generate table alike to yours
DECLARE #yourTable TABLE ([value] varchar(max))
-- convert array to xml
;WITH cte AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn,
[response],
CAST('<a>'+REPLACE(SUBSTRING([response],2,LEN([response]) - 2),',','</a><a>')+'</a>' as xml) AS x,
#v_UserId AS UserId,
[item_identifier]
FROM
#TempColumns
LEFT JOIN
YS_BAB_response_dump ON YS_BAB_response_dump.Item_Identifier = #TempColumns.Calculate_ItemIdentifier
AND UserId = CAST(#UserId AS VARCHAR(MAX))
AND TestModel = 'IR'
)
-- do the stuff
SELECT
c.rn,
c.[response],
c.[item_identifier],
RIGHT(#zero_str +
CAST(SUM(CAST(STUFF(#zero_str,t.c.value('.','tinyint')+1,1,'1') AS INT)) AS VARCHAR(6)), 6) AS ans,
c.UserId
FROM
cte c
CROSS APPLY
x.nodes('/a') AS t(c)
GROUP BY
c.rn, c.[response], c.UserId, c.[Item_Identifier]
ORDER BY
c.rn
COMMIT TRAN
What changes I need to do in above procedure to get 25 records as a result instead of 22, For IR21,IR22 and IR25 I want null data in response and ans columns for that respective userId? May i need to use some other function instead of CROSS APPLY? How it will be?
You were almost there. Use OUTER APPLY instead of CROSS APPLY
In T-SQL I want to loop through a table in a stored procedure, by reading a row by row.
DECLARE #IMAX INT,
#ICOUNT INT,
#INTERFACE_ID_36 INT,
#INTERFACE_ID_38 INT
SELECT * FROM INTERFACE_36_DATA
SET #IMAX = ##ROWCOUNT
SET #ICOUNT = 1
WHILE(#ICOUNT <= #IMAX)
BEGIN
SELECT #INTERFACE_ID_36 = Interface_ID
FROM INTERFACE_36_DATA
WHERE ROW_NUMBER() OVER (ORDER BY id) AS = #ICOUNT --syntax error here
IF #INTERFACE_ID_36 = 10
SET #INTERFACE_ID_38 = 0
ELSE IF #INTERFACE_ID_36 =
I suggest to rewrite it using Cursors as follows faster:
DECLARE #IMAX INT,
#ICOUNT INT,
#INTERFACE_ID_36 INT,
#INTERFACE_ID_38 INT
DECLARE db_cursor CURSOR FOR
SELECT Interface_ID FROM INTERFACE_36_DATA
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #INTERFACE_ID_36
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #INTERFACE_ID_36
-- All your other selects
FETCH NEXT FROM db_cursor INTO #INTERFACE_ID_36
END
CLOSE db_cursor
DEALLOCATE db_cursor
Change your query like below.
As we can't use row_number in where condition.
Check the link here for more descr
WITH cte
AS ( SELECT Interface_ID ,
ROW_NUMBER() OVER ( ORDER BY id ) AS RN
FROM INTERFACE_36_DATA
)
SELECT #INTERFACE_ID_36 = Interface_ID
FROM cte
WHERE RN = #ICOUNT
You can try doing this :
DECLARE #IMAX INT,
#ICOUNT INT,
#INTERFACE_ID_36 INT,
#INTERFACE_ID_38 INT
select *,ROW_NUMBER() OVER (ORDER BY Interface_ID) RowId into #tmptbl from INTERFACE_36_DATA
Declare #I BIGINT = 1
declare #count BIGINT = (select Count(*) from #tmptbl)
while(#I < = #count)
begin
SELECT #INTERFACE_ID_36 = Interface_ID
FROM #tmptbl
where RowId = #I
--- do yor additional stuff
set #I =#I +1
end
Can I create a view or function using the below query? It uses temp tables. I am not able to create either a view or function.
--TEmp table--
IF OBJECT_ID('tempdb..#Enquiries') IS NOT NULL
DROP TABLE #Enquiries
GO
CREATE TABLE #Enquiries
(ID INT,PID INT,Name VARCHAR(50),Enquiries INT,EnquiryDate datetime)
INSERT INTO #Enquiries
SELECT ROW_NUMBER()
OVER (ORDER BY ProjectName) AS Row, (SELECT top 1 ITEM FROM DBO.split(e.InterestedProjects,',')) as Projects,P.ProjectName,COUNT(CAST(EnquiryDate AS DATE)) AS Enquiries,CAST(EnquiryDate AS DATE) AS EnquiryDate
FROM tbl_Enquiry e INNER JOIN
tbl_Projects AS P ON P.ProjectId = (SELECT TOP 1 ITEM FROM DBO.split(e.InterestedProjects,','))
WHERE e.IsActive=1 and e.isdeleted=0 AND p.IsActive=1 AND p.IsDeleted=0 AND P.ProjectId IN (SELECT TOP 1 ITEM FROM DBO.split(e.InterestedProjects,','))
GROUP BY e.InterestedProjects,P.ProjectName,CAST(EnquiryDate AS DATE)
--SiteVisits
IF OBJECT_ID('tempdb..#SiteVisit') IS NOT NULL
DROP TABLE #SiteVisit
GO
CREATE TABLE #SiteVisit
(ID INT,PID INT,Name VARCHAR(50),Sitevisits INT,PickUpDatetime datetime)
INSERT INTO #SiteVisit
SELECT ROW_NUMBER() OVER (ORDER BY ProjectName) AS Row,s.ProjectId,p.ProjectName As Name,count(sd.PickUpDatetime) AS Sitevisits,CAST(PickUpDatetime AS DATE) AS PickUpDatetime FROM tbl_SiteVisit s
INNER JOIN tbl_SiteVisitDetails sd ON s.SiteVisitId=sd.SiteVisitId
INNER JOIN tbl_Projects p ON p.ProjectId=s.ProjectId
WHERE s.IsActive=1 and s.isdeleted=0 AND sd.isactive=1 AND sd.isdeleted=0
GROUP BY s.ProjectId,sd.PickUpDatetime,p.ProjectName,CAST(PickUpDatetime AS DATE)
--Bookings
IF OBJECT_ID('tempdb..#Bookings') IS NOT NULL
DROP TABLE #Bookings
GO
CREATE TABLE #Bookings
(ID INT,PID INT,Name VARCHAR(50),Bookings INT,BookingDate datetime,Revenue money,Area float)
INSERT INTO #Bookings
SELECT ROW_NUMBER() OVER (ORDER BY ProjectName) AS Row, u.ProjectId AS ProjectId,p.ProjectName,count(u.ProjectId) AS Bookings,CAST(b.BookingDate AS DATE) AS BookingDate,SUM(b.TotalAmount) AS [Revenue],SUM(u.UnitArea) AS [Area] FROM tbl_Bookings b
INNER JOIN tbl_Unit u ON b.UnitId=u.UnitId
INNER JOIN tbl_Projects p on p.ProjectId=u.ProjectId
WHERE b.IsActive=1 AND b.IsDeleted=0 and u.IsActive=1 AND u.IsDeleted=0 AND u.Status = 'B'
GROUP BY u.ProjectId,p.ProjectName,CAST(b.BookingDate AS DATE),b.TotalAmount,u.UnitArea
--ORDER BY u.ProjectId
IF OBJECT_ID('tempdb..#T1') IS NOT NULL
DROP TABLE #T1
create TABLE #T1 (
PrimaryNo INT,
EnquiryDate Date,
Enquiries INT,
SiteVisits INT,
Bookings INT,
Revenue Money,
Area Float,
PID INT,
ProjectName nvarchar(max)
)
INSERT INTO #T1(PrimaryNo,EnquiryDate,Enquiries,PID,ProjectName)
SELECT ID,EnquiryDate,sum(enquiries) AS Enquiries,PID,Name FROM #Enquiries GROUP BY id,pid,Name,enquirydate
DECLARE #SVDate date
DECLARE #SV11 INT
DECLARE #BookingDate Date
DECLARE #Bookings11 INT
DECLARE #Revenue11 MONEY
DECLARE #Area11 FLOAT
DECLARE #intFlag_pw11 INT
SET #intFlag_pw11 = 1
DECLARE #TableCntw11 INT
DECLARE #Date Date
DECLARE Cur_SiteVisit CURSOR FAST_FORWARD FOR
SELECT PickUpDatetime FROM #SiteVisit
OPEN Cur_SiteVisit
FETCH NEXT FROM Cur_SiteVisit INTO #Date
DECLARE #ProjectId INT
DECLARE #Count INT = 1
WHILE ##FETCH_STATUS = 0
BEGIN
SET #ProjectId = (SELECT PID FROM #SiteVisit WHERE ID = #Count)
SET #SVDate = ISNULL((SELECT CAST(PickUpDatetime AS DATE) FROM #SiteVisit
WHERE CAST(PickUpDatetime AS DATE) = #Date AND PID = #ProjectId
GROUP BY PickUpDatetime),'-')
SET #SV11 = ISNULL((SELECT Sitevisits FROM #SiteVisit
WHERE CAST(PickUpDatetime AS DATE) = #Date AND PID = #ProjectId
GROUP BY Sitevisits),0)
EXEC ('UPDATE #T1 SET SiteVisits = ' + #SV11 + ' WHERE EnquiryDate = ' + ''''+ #SVDate +''' AND PID =' + #ProjectId)
FETCH NEXT FROM Cur_SiteVisit INTO #Date
SET #Count = #Count + 1
END
CLOSE Cur_SiteVisit
DEALLOCATE Cur_SiteVisit
--For Bookings
DECLARE #Date1 Date
DECLARE Cur_Bookings CURSOR FAST_FORWARD FOR
SELECT BookingDate FROM #Bookings
OPEN Cur_Bookings
FETCH NEXT FROM Cur_Bookings INTO #Date1
DECLARE #ProjectId1 INT
DECLARE #Count1 INT = 1
WHILE ##FETCH_STATUS = 0
BEGIN
SET #ProjectId1 = (SELECT PID FROM #Bookings WHERE ID = #Count1)
SET #Bookings11 = ISNULL((SELECT TOP 1 Bookings FROM #Bookings
WHERE CAST(BookingDate AS DATE) = #Date1 AND PID = #ProjectId1
GROUP BY Bookings),0)
SET #BookingDate = ISNULL((SELECT TOP 1 CAST(BookingDate AS DATE) FROM #Bookings
WHERE CAST(BookingDate AS DATE) = #Date1 AND PID = #ProjectId1
GROUP BY CAST(BookingDate AS DATE)),'-')
SET #Revenue11 = ISNULL((SELECT TOP 1 Revenue FROM #Bookings
WHERE CAST(BookingDate AS DATE) = #Date1 AND PID = #ProjectId1
GROUP BY Revenue),0)
SET #Area11 = ISNULL((SELECT TOP 1 Area FROM #Bookings
WHERE CAST(BookingDate AS DATE) = #Date1 AND PID = #ProjectId1
GROUP BY Area),0)
EXEC ('UPDATE #T1 SET Bookings = ' + #Bookings11 + ',Revenue=' + #Revenue11 + ',Area = ' + #Area11 + ' WHERE EnquiryDate = ' + '''' + #BookingDate + ''' AND PID =' + #ProjectId1)
FETCH NEXT FROM Cur_Bookings INTO #Date1
SET #Count1 = #Count1 + 1
END
CLOSE Cur_Bookings
DEALLOCATE Cur_Bookings
Select * from #T1
You can't create a view from that, if only because you're doing a number of inserts and other actions. A view is created from a single query.
With regard to user-defined functions: you cannot use dynamic SQL, which you are doing:
EXEC ('UPDATE #T1 SET Bookings = ' + #Bookings11 + ',Revenue=' + #Revenue11 +
',Area = ' + #Area11 + ' WHERE EnquiryDate = ' + '''' + #BookingDate +
''' AND PID =' + #ProjectId1)
You also can't use temp tables. Both of these limitations are documented here: http://msdn.microsoft.com/en-us/library/ms191320.aspx.
But, you can do all of these things in a stored procedure. It is also possible to direct the output of a stored procedure to a temp table or table variable, allowing you to use the output in another query:
INSERT INTO dbo.MyTable
(MyTableId, Column1, Column2) -- arbitrary-chosen column names
EXEC dbo.MyStoredProcedure
SELECT *
FROM dbo.MyTable
WHERE Column1 = 'Some Value'
Finally, you might be able to rework your SQL to work with table variables rather than temp tables, which are allowed. It also looked to me like your dynamic SQL didn't need to be dynamic, so you might be able to eliminate that as well.
Hope this helps.
I can't find the Syntax Error in the following Query:
USE [Contact Manager]
GO
-- Define the Procedure
ALTER PROCEDURE [dbo].[sp_delete_Contact]
#contactID INT
AS
BEGIN
-- SET NOCOUNT OFF added enable Counting
SET NOCOUNT OFF;
-- Determine all Phone Numbers with a Single Link to the specified Contact
CREATE TABLE #PhoneNumbers (phone_number INT NOT NULL PRIMARY KEY)
INSERT #PhoneNumbers (phone_number)
SELECT phone_number
FROM Contact_PhoneNumber
WHERE phone_number IN
(
SELECT phone_number
FROM Contact_PhoneNumber
GROUP BY phone_number
HAVING COUNT(*) = 1
)
AND contact = #contactID
-- Declare Loop Variables
DECLARE #i int = 0
DECLARE #count int = (SELECT COUNT(*) FROM #PhoneNumbers)
-- Delete all Phone Numbers with a Single Link to the specified Contact
WHILE #i < #count
EXEC sp_delete_PhoneNumber
(
SELECT phone_number, ROW_NUMBER()
OVER (ORDER BY phone_number) AS row_num
FROM #PhoneNumbers
WHERE row_num = #i
)
SET #i = #i + 1
END
-- Determine all Addresses with a Single Link to the specified Contact
CREATE TABLE #Addresses ([address] INT NOT NULL PRIMARY KEY)
INSERT #Addresses ([address])
SELECT [address]
FROM Contact_Address
WHERE [address] IN
(
SELECT [address]
FROM Contact_Address
GROUP BY [address]
HAVING COUNT(*) = 1
)
AND contact = #contactID
-- Reset Loop Variables
SET #i = 0
SET #count = (SELECT COUNT(*) FROM #Addresses)
-- Delete all Addresses with a Single Link to the specified Contact
WHILE #i < #count
EXEC sp_delete_Address
(
SELECT [address], ROW_NUMBER()
OVER (ORDER BY [address]) AS row_num
FROM #Addresses
WHERE row_num = #i
)
SET #i = #i + 1
END
-- Determine all Emails with a Single Link to the specified Contact
CREATE TABLE #Emails (email INT NOT NULL PRIMARY KEY)
INSERT #Emails (email)
SELECT email
FROM Contact_Email
WHERE email IN
(
SELECT email
FROM Contact_Email
GROUP BY email
HAVING COUNT(*) = 1
)
AND contact = #contactID
-- Reset Loop Variables
SET #i = 0
SET #count = (SELECT COUNT(*) FROM #Emails)
-- Delete all Emails with a Single Link to the specified Contact
WHILE #i < #count
EXEC sp_delete_Email
(
SELECT email, ROW_NUMBER()
OVER (ORDER BY email) AS row_num
FROM #Emails
WHERE row_num = #i
)
SET #i = #i + 1
END
-- Determine all Groups with a Single Link to the specified Contact
CREATE TABLE #Groups ([group] INT NOT NULL PRIMARY KEY)
INSERT #Groups ([group])
SELECT [group]
FROM Member
WHERE [group] IN
(
SELECT [group]
FROM Member
GROUP BY [group]
HAVING COUNT(*) = 1
)
AND contact = #contactID
-- Reset Loop Variables
SET #i = 0
SET #count = (SELECT COUNT(*) FROM #Groups)
-- Delete all Groups with a Single Link to the specified Contact
WHILE #i < #count
EXEC sp_delete_Group
(
SELECT [group], ROW_NUMBER()
OVER (ORDER BY [group]) AS row_num
FROM #Emails
WHERE row_num = #i
)
SET #i = #i + 1
END
END
Any help with this would be greatly appreciated.
The comments should let you know what I'm trying to do, but I'm pretty certain that the logic behind the code is solid. I just don't know where the syntax errors are.
When I try to run the query to alter to stored procedure, I get the following errors:
Msg 156, Level 15, State 1, Procedure sp_delete_Contact, Line 81
Incorrect syntax near the keyword 'CREATE'.
Msg 156, Level 15, State 1, Procedure sp_delete_Contact, Line 113
Incorrect syntax near the keyword 'CREATE'.
Msg 156, Level 15, State 1, Procedure sp_delete_Contact, Line 143
Incorrect syntax near the keyword 'END'.
-- Define the Procedure
CREATE PROCEDURE [dbo].[sp_delete_Contact]
#contactID INT
AS
BEGIN
-- SET NOCOUNT OFF added enable Counting
SET NOCOUNT OFF;
-- Determine all Phone Numbers with a Single Link to the specified Contact
CREATE TABLE #PhoneNumbers (phone_number INT NOT NULL PRIMARY KEY)
INSERT #PhoneNumbers (phone_number)
SELECT phone_number
FROM Contact_PhoneNumber
WHERE phone_number IN
(
SELECT phone_number
FROM Contact_PhoneNumber
GROUP BY phone_number
HAVING COUNT(*) = 1
)
AND contact = #contactID
-- Declare Loop Variables
DECLARE #i int = 0
DECLARE #count int = (SELECT COUNT(*) FROM #PhoneNumbers)
-- Delete all Phone Numbers with a Single Link to the specified Contact
WHILE #i < #count
BEGIN
EXEC sp_delete_PhoneNumber
(
SELECT phone_number, ROW_NUMBER()
OVER (ORDER BY phone_number) AS row_num
FROM #PhoneNumbers
WHERE row_num = #i
)
SET #i = #i + 1
END
-- Determine all Addresses with a Single Link to the specified Contact
CREATE TABLE #Addresses ([address] INT NOT NULL PRIMARY KEY)
INSERT #Addresses ([address])
SELECT [address]
FROM Contact_Address
WHERE [address] IN
(
SELECT [address]
FROM Contact_Address
GROUP BY [address]
HAVING COUNT(*) = 1
)
AND contact = #contactID
-- Reset Loop Variables
SET #i = 0
SET #count = (SELECT COUNT(*) FROM #Addresses)
-- Delete all Addresses with a Single Link to the specified Contact
WHILE #i < #count
BEGIN
EXEC sp_delete_Address
(
SELECT [address], ROW_NUMBER()
OVER (ORDER BY [address]) AS row_num
FROM #Addresses
WHERE row_num = #i
)
SET #i = #i + 1
END
-- Determine all Emails with a Single Link to the specified Contact
CREATE TABLE #Emails (email INT NOT NULL PRIMARY KEY)
INSERT #Emails (email)
SELECT email
FROM Contact_Email
WHERE email IN
(
SELECT email
FROM Contact_Email
GROUP BY email
HAVING COUNT(*) = 1
)
AND contact = #contactID
-- Reset Loop Variables
SET #i = 0
SET #count = (SELECT COUNT(*) FROM #Emails)
-- Delete all Emails with a Single Link to the specified Contact
WHILE #i < #count
BEGIN
EXEC sp_delete_Email
(
SELECT email, ROW_NUMBER()
OVER (ORDER BY email) AS row_num
FROM #Emails
WHERE row_num = #i
)
SET #i = #i + 1
END
-- Determine all Groups with a Single Link to the specified Contact
CREATE TABLE #Groups ([group] INT NOT NULL PRIMARY KEY)
INSERT #Groups ([group])
SELECT [group]
FROM Member
WHERE [group] IN
(
SELECT [group]
FROM Member
GROUP BY [group]
HAVING COUNT(*) = 1
)
AND contact = #contactID
-- Reset Loop Variables
SET #i = 0
SET #count = (SELECT COUNT(*) FROM #Groups)
-- Delete all Groups with a Single Link to the specified Contact
WHILE #i < #count
BEGIN
EXEC sp_delete_Group
(
SELECT [group], ROW_NUMBER()
OVER (ORDER BY [group]) AS row_num
FROM #Emails
WHERE row_num = #i
)
SET #i = #i + 1
END
END
When executing More than One statement After While Condition you need to put them in BEGIN END block
And, I figured it out.
The example that I looked at for WHILE loops didn't mention that I needed a BEGIN to match the END.
So yeah:
WHILE (boolean)
BEGIN
-- Do Stuff
END