Subquery is not introduced with exists, stored procedure - sql

I've made a stored procedure and got the error message below, dont know why. I've been looking around for some answers and with some other guys here at the office but they're all unsure of the problem. Hoping someone here has had the same problem and knows the solution to this.
Msg 116, Level 16, State 1, Procedure Name_Stored_Procedure,
Line 113 Only one expression can be specified in the select list
when the subquery is not introduced with EXISTS.
Here is my Code
Set #SQLstring =
'Update #TempTable set Col1' + case when len(Convert(Varchar, (4+#counter)))=1
then '0' else '' end
+ Convert(Varchar,(4+#counter)) + '=''' +
(select #Year, #Month,
Convert(Varchar,count(distinct Table.Column1))
from Databse.Table
where DATEPART(yy,Time) = #Year
and DATEPART(mm,Time) = #Month
and Table.Column2 = #Column2 and Column3 in ('X','Z','Y - A'))
+''' where row = ' + CONVERT(varchar,10+#somevariable * 12)
exec('' + #SQLstring +'')

If you're going to build a string of SQL and execute it with dynamic SQL, then you need to treat it as a string
Set #SQLstring =
'Update #TempTable set Col'
+ case when len(Convert(Varchar, (4+#counter)))=1 then '0' else '' end
...
In your inner select, remove the #year, #month from the results
+ ( select Convert(Varchar,count(distinct Table.Column1)) from databse.Table....

Take the year , month , count in the below part in separate select queries.
(select #Year, #Month,
Convert(Varchar,count(distinct Table.Column1))
from Databse.Table
where DATEPART(yy,Time) = #Year
and DATEPART(mm,Time) = #Month
and Table.Column2 = #Column2 and Column3 in ('X','Z','Y - A'))

select CONCAT(#year, #month, convert....)

Related

Stored Procedure error "Must declare the scalar variable"

I have written a stored procedure to extract data from a table in SQL Server:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[csp_OperatorVarianceMonthlyView]
-- =============================================
-- Procedure: csp_OperatorVarianceMonthlyView
--
-- Summary: Produce the result table that is needed for the Operator Variance Tracker report.
--
-- Params: #RetailStoreId - Store Id on which the results need to be filtered
-- #StartDate - The start business day date for which results are to be collected (NULL = Today)
-- #EndDate - The end business day date for which results are to be collected (NULL = Today)
-- #OperatorIDList - OperatorID comma seperated list
-- Returns: A result set to populate a Operator Variance Report tab
--
-- Version: 2013-06-25 11:00
-- ==============================================
#TenantID t_ID,
#RetailStoreID t_ID,
#StartDate t_Timestamp = null,
#EndDate t_Timestamp = null,
#OperatorIDList varchar(500)=null
AS
IF 1 = 0
BEGIN
SET FMTONLY OFF
END
BEGIN
declare #SQL nvarchar(2500)
declare #StartBusinessDayDate t_TimeStamp
declare #EndBusinessDayDate t_TimeStamp
declare #StartDateOfYear t_TimeStamp
declare #StartDateOfMonth t_TimeStamp
declare #Sunday t_TimeStamp
declare #FirstSundayOfMonth t_TimeStamp
SET NOCOUNT ON;
if (#StartDate is null)
select #StartDate = GETDATE()
if (#EndDate is null)
select #EndDate = GETDATE()
-- Eliminate any time information that might be in the Start/End dates
select #StartBusinessDayDate = convert(varchar(8), cast (#StartDate as datetime), 112)
select #EndBusinessDayDate = convert(varchar(8), cast (#EndDate as datetime), 112)
-- Compute StartDateOfYear and StartDateOfMonth to compute the YTD and MTD variances
set #StartDateOfYear = DATEADD(year, DATEDIFF(year, 0, #EndBusinessDayDate),0)
set #StartDateOfMonth = DATEADD(month, DATEDIFF(month, 0, #EndBusinessDayDate), 0)
-- Select a Sunday
set #Sunday = '2017-01-01'
-- Get first Sunday of the month for getting week-wise data for the OVT report
set #FirstSundayOfMonth = DATEADD(WEEK, DATEDIFF(WEEK, #Sunday, #StartBusinessDayDate), #Sunday)
-- Create temporary tables to hold the monthly and yearly variance amounts for each operator
Create table #TempOperatorVarianceYTD ([OperatorID] int, [VarianceAmtYTD] decimal)
Create table #TempOperatorVarianceMTD ([OperatorID] int, [VarianceAmtMTD] decimal)
-- Insert Year To Date (YTD) variance amounts by operator to the tempoarary table
Insert into #TempOperatorVarianceYTD
Select OperatorID, sum(NetOverShortAmount)
from TillBalanceExceptionPTDSummary
where BusinessDayDate between #StartDateOfYear and #EndBusinessDayDate
and RetailStoreID = #RetailStoreID
and PeriodTypeCode = 1
group by OperatorID
-- Insert Month To Date (MTD) variance amounts by operator to the tempoarary table
Insert into #TempOperatorVarianceMTD
Select OperatorID, sum(NetOverShortAmount)
from TillBalanceExceptionPTDSummary
where BusinessDayDate between #StartDateOfMonth and #EndBusinessDayDate
and RetailStoreID = #RetailStoreID
and PeriodTypeCode = 1
group by OperatorID
-- Build the SQL statement to get the result table for the monthly view of the Operator Variance Tracker report.
select #SQL = 'Select TBES.OperatorID as OperatorID, ' +
'O.[Name] as OperatorName, ' +
'YTD = YTD.VarianceAmtYTD, ' +
'MTD = MTD.VarianceAmtMTD, ' +
'Week1 = SUM(CASE WHEN TBES.PeriodTypeCode = 2 AND TBES.BusinessDayDate = #FirstSundayOfMonth THEN TBES.NetOverShortAmount ELSE 0 END), ' +
'Week2 = SUM(CASE WHEN TBES.PeriodTypeCode = 2 AND TBES.BusinessDayDate = DATEADD(WEEK, 1, #FirstSundayOfMonth) THEN TBES.NetOverShortAmount ELSE 0 END), ' +
'Week3 = SUM(CASE WHEN TBES.PeriodTypeCode = 2 AND TBES.BusinessDayDate = DATEADD(WEEK, 2, #FirstSundayOfMonth) THEN TBES.NetOverShortAmount ELSE 0 END), ' +
'Week4 = SUM(CASE WHEN TBES.PeriodTypeCode = 2 AND TBES.BusinessDayDate = DATEADD(WEEK, 3, #FirstSundayOfMonth) THEN TBES.NetOverShortAmount ELSE 0 END), ' +
'Week5 = SUM(CASE WHEN TBES.PeriodTypeCode = 2 AND TBES.BusinessDayDate = DATEADD(WEEK, 4, #FirstSundayOfMonth) THEN TBES.NetOverShortAmount ELSE 0 END) ' +
'FROM [postrn001].[dbo].[TillBalanceExceptionPTDSummary] TBES ' +
'join [posfdn001].[dbo].[Operator] O ' +
'on TBES.OperatorID = O.OperatorID ' +
'join #TempOperatorVarianceYTD YTD ' +
'on O.OperatorID = YTD.OperatorID ' +
'join #TempOperatorVarianceMTD MTD ' +
'on O.OperatorID = MTD.OperatorID ' +
'where TBES.RetailStoreID = #RetailStoreID '
-- Add the operator filter if necessary
if ( NOT (#OperatorIDList is null) )
begin
-- Avoid sql injection by cleaning the string
set #OperatorIDList = REPLACE(#OperatorIDList, ';', '')
set #OperatorIDList = REPLACE(#OperatorIDList, ')', '')
set #OperatorIDList = REPLACE(#OperatorIDList, '-', '')
select #SQL = #SQL + 'and TBES.OperatorID IN (' + #OperatorIDList + ') '
end
--Add the group by clause
select #SQL = #SQL + 'group by TBES.OperatorID, O.[Name], YTD.VarianceAmtYTD, MTD.VarianceAmtMTD'
print #SQL
print #FirstSundayOfMonth
exec sp_executesql #SQL,
N'#TenantID t_ID, #RetailStoreId t_ID, #StartBusinessDayDate t_TimeStamp, #EndBusinessDayDate t_TimeStamp, #OperatorIDList varchar(500)',
#TenantID, #RetailStoreId, #StartBusinessDayDate, #EndBusinessDayDate, #OperatorIDList
return ##error
-- Drop the temporary tables.
drop table #TempOperatorVarianceMTD, #TempOperatorVarianceYTD
END
Upon executing this, I get this error:
Must declare the scalar variable "#FirstSundayOfMonth"
As you can see in the code, I have declared and initialized the value of #FirstSundayOfMonth in the stored procedure.
I'm not sure on what I might be missing here - I tried copying the query part to a separate window and executing it after assigning the values to the declared variables and it executes and generates the result that I expect.
I'm guessing I'm missing something minor but I'm unable to figure out what it is.
Any leads on this would be great!
The variable declared in the outer scope is not visible to the dynamic SQL statement. Pass #FirstSundayOfMonth as another parameter to sp_executesql.

While Loop Issue

Hoping that someone can offer some assistance, I am currently working on a piece of code which seems to be having issues. Unfortunately I cant post the underlying data but will try and explain.
The code currently cycles through a selection of kpi's and calculates if something needs to be run or not based on the current time and whether the individual kpi's need to be run. At the moment if I hard code a number of kpi's the code works fine but if I let it cycle through all the kpi's, ones that should not run are being told to run, also in the select that defines things like #Period, when I let it run through all KPI's its setting the #Period incorrectly when it shouldn't run but when its meant to run it set it fine.
Overall I have 2 issues which I think are related KPI's run when they are not meant to and when they are running when they are not meant to they pick up the wrong Period either way which is odd. I think what is happening is when I let it run all the way through the KPI's are getting mixed up but I cant see how this is happening, any help would be great before I go mad.
As you can see from my code there are 2 #current_timestamps, when its set to 23.45.18.873 it should not run some of the kpi's but it runs them all anyway and the 21.45.18.873 means that they can run.
declare #job_current_time_minute float,
#job_current_date_time_minute as datetime,
#current_timestamp as datetime
SET #job_current_time_minute = 52--cast(datepart(minute, getdate()) as float)
SET #job_current_date_time_minute = getdate()
--SET #current_timestamp = cast('2017-04-02 23:45:18.873' as datetime)
SET #current_timestamp = cast('2017-04-02 21:45:18.873' as datetime)
--Run: 88 6 0 52 5 5 5
--Run: 88 1 10 52 5 5 5
declare
#kpi_id int,
#kpi_parent_id int,
#sql nvarchar(max),
#kpi_last_result nvarchar(100),
#kpi_last_runtime datetime,
#kpi_params nvarchar(max),
#kpi_current_time_minute float,
#schedulue_minute float,
#reoccurrence float,
#result float,
#kpi2 int,
-- Email Variables
#kpi_name nvarchar(150),
#kpi_desc nvarchar(150),
#kpi_report_link nvarchar(150),
#kpi_email_subject nvarchar(150),
#kpi_email_body nvarchar(300),
#kpi_email_query nvarchar(max),
#kpi_sms_msg nvarchar(300);
SET #kpi_params = N'#retvalOUT varchar(max) OUTPUT';
select #kpi_id = min(kpi_id) from KPI where KPI_Active = 1; --and kpi_id in (86, 88)
while #kpi_id is not null
begin
select
#kpi_parent_id = kpi_parent_id,
#sql = kpi_Script,
#schedulue_minute = datepart(minute,s.Schedule_Start),
#reoccurrence = s.Reoccurrence,
#result = cast((#job_current_time_minute - datepart(minute,s.Schedule_Start)) / s.Reoccurrence as decimal(18,2)),
#kpi_name = kpi_name,
#kpi_desc = kpi_desc,
#kpi_report_link = kpi_report_link,
#kpi_email_subject = kpi_email_subject,
#kpi_email_body = kpi_email_body,
#kpi_email_query = kpi_email_query,
#kpi_sms_msg = kpi_sms_msg,
#kpi_current_time_minute = 60*DATEPART(HOUR, GETDATE())+DATEPART(MINUTE,GETDATE()),
#kpi2 = KPI_ID
from EWI..KPI
inner join EWI..Schedule s on KPI.Schedule_ID = s.Schedule_ID where kpi_id = #kpi_id--order by kpi_id asc
--set #sql = 'select #retvalOUT= (' + #sql + ')'
if floor(#result) <> ceiling(#result)
begin
PRINT 'Not Time to Run: ' + ' ' + cast(#kpi_id as varchar(11)) + ' ' + cast(#result as varchar(11))
end
else
begin
declare
#ThresholdID int,
#PeriodID int,
#Threshold_value int,
#Threshold_PosNeg nvarchar(5)
select #ThresholdID = Threshold_ID, #PeriodID = Period_ID, #Threshold_value = Threshold_value, #Threshold_PosNeg = Threshold_PosNeg from (
-- select * from (
select * from (
select KPI_ID, t.Threshold_ID, p.Period_ID, t.Threshold_Value, t.Threshold_PosNeg, p.DayStartTime, p.DayEndTime, Period_desc, [Day]
from EWI..Threshold t join
EWI..Period p on t.Period_ID = p.Period_ID where KPI_ID = #kpi_id
) x where (case when [Day] = datename(dw,getdate()) then Period_id
when [Day] = choose(datepart(dw, getdate()), 'WEEKEND','Weekday','Weekday','Weekday','Weekday','Weekday','WEEKEND') then Period_ID
when [Day] = 'All' then Period_ID end) is not null
) y where case when datediff(second,DayStartTime,DayEndTime) > 0 then
case when convert(time(0), #current_timestamp) >= DayStartTime and convert(time(0), #current_timestamp) < DayEndTime then 1 else 0 end
else case when convert(time(0), #current_timestamp) >= DayStartTime or convert(time(0), #current_timestamp) < DayEndTime then 1 else 0 end
end = 1
select 'Run: ' + cast(#kpi_id as varchar(11)) + ' ' + cast(#PeriodID as varchar(11)) + ' ' +
cast(#Threshold_value as varchar(11)) + ' ' + cast(#job_current_time_minute as varchar(11)) + ' ' +
cast(#result as varchar(11)) + ' ' +
cast(ceiling(#result) as varchar(11))+ ' ' +cast(floor(#result) as varchar(11))
end
select #kpi_id = min(kpi_id) from KPI where KPI_Active = 1 and kpi_id > #kpi_id;
end
Take a look at this rextester demo. Do you agree that this model reproduces the problem? It seems that comparing ceiling(#result) to floor(#result) will indeed give everywhere true.
After our discussion it seems to me that the test should be:
if (#result - datepart(minute, Schedule_Start)) % #reoccurrence = 0
or something like that. But this assumes #reoccurence to be an integer.

Grouping within a While Loop, SQL Server

I've been building a while loop to populate a lot of data, and I'm struggling with grouping within the query - I want to add a group on Membership_Level but each time it is returning identical values (the total) for each Level.
Can anyone help me?
Thank you in advance!!!
DECLARE #Counter int
DECLARE #NumPerson int
SET #Counter = 1
WHILE #Counter <= 12
BEGIN
SET #NumPerson = (SELECT
SUM(Amount)
FROM [NewMember]
WHERE LEFT([PERIOD], 4) = 2016
AND GRADE_STATUS = 'N'
AND RIGHT([Period], 2) = #Counter)
SELECT
*
FROM (SELECT
CAST(#NumPerson AS varchar(6)) AS 'Number',
CASE
WHEN LEN(CAST(#Counter AS varchar(2))) = 1 THEN '0' + CAST(#Counter AS varchar(2))
ELSE CAST(#Counter AS varchar(2))
END AS 'Month') s
JOIN (SELECT
MAX('1') AS NGroup,
[PERIOD],
RIGHT([Period], 2) AS 'Month',
MEMBERSHIP_LEVEL
FROM [NewMember]
WHERE LEFT([PERIOD], 4) = 2016
AND GRADE_STATUS = 'N'
GROUP BY [MEMBERSHIP_LEVEL],
[PERIOD],
RIGHT([Period], 2)) t
ON s.[Month] = t.[Month]
SET #Counter = #Counter + 1
END

SQL Server 2012 error: each GROUP BY expression must contain at least one column that is not an outer reference

My code is like this
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER PROCEDURE [dbo].[getprocbyproc]
#flg varchar(2),
#qaaprvdt char(8),
#dbo varchar(20),
#plantid char(1)
AS
DECLARE #dynamicSQL varchar(8000)
DECLARE #datemth char(6)
DECLARE #dateday char(2)
DECLARE #FXTIME char(4)
DECLARE #TBL varchar(20)
DECLARE #def varchar(20)
DECLARE #OUTDAT CHAR(20)
SET #datemth = substring(#qaaprvdt,1,6)
SET #dateday = substring(#qaaprvdt,7,2)
IF #flg = 'QA' AND #dbo = 'PRCDAILYQA'
BEGIN
SET #TBL = 'DAILYQA'
SET #OUTDAT = 'CO.QAAPRVDT'
END
IF #plantid = '1'
BEGIN
SET #def = "SQDPRCDEF1"
END
IF #flg = 'QA' AND #plantid = '1'
BEGIN
SET #dynamicSQL = 'insert into PrcdailyQA' +
'(process, seqno, qaamon, qaaday, orderno,
ingotno, theopcs, cwacc, pwacc, pwout,
procyld, prodyld, plantid, prodline) ' +
'(SELECT distinct(b.PROCNO), b.proseq, "' +
#datemth + '" , "' + #dateday +
'", a.orderno, a.ingotno, a.theopcs, a.cwacc, a.pwacc, a.pwout, a.COprocyld, a.COprodyld, a.plantid, a.prodline ' +
'FROM DailyQA a , SQDPRCDEF1 b ' +
'WHERE a.qaamon = ' + #datemth + ' and a.qaaday= ' + #DATEDAY + ' and a.plantid="1"' +
'GROUP BY b.procno, b.proseq, a.orderno, a.ingotno, a.theopcs, a.cwacc, a.pwacc, a.pwout, a.COprocyld, a.COprodyld, a.plantid, a.prodline) '
Now when I to execute it returns no error. But when I try to execute it at runtime, it returns error
Msg 164, Level 15, State 1, Line 1
Each GROUP BY expression must contain at least one column that is not an outer reference.
I already refer this http://www.sql-server-performance.com/2007/group-by-expression-contain-one-column-not-an-outer-reference/ and try to change the group by statement, also return error.
Please help!
Because you are not aggregating on any fields (i.e. using sum, max, etc.), you don't really need to use a group by clause in your example.
However, what are you trying to do in the from clause? You are currently creating a cartesian product of the 2 tables -- you aren't joining the tables on any common field.
Without knowing more, I'd be more inclined to remove the group by clause altogether, and have something like this:
insert into ...
select distinct b.PROCNO, b.proseq, ...
from ...
where ...
Btw, in general I wouldn't recommend using commas in a from clause, use join instead.
You don't need DISTINCT in a GROUP BY query. Also, you are selecting columns which do not either appear in the GROUP BY clause or are aggregates of columns. Removing DISTINCT along with the non-aggregate columns would leave you with the following query:
INSERT INTO PrcdailyQA (process, seqno, qaamon, qaaday, orderno, ingotno, theopcs, cwacc,
pwacc, pwout, procyld, prodyld, plantid, prodline)
SELECT b.PROCNO, b.proseq, a.orderno, a.ingotno, a.theopcs, a.cwacc, a.pwacc, a.pwout,
a.COprocyld, a.COprodyld, a.plantid, a.prodline
FROM DailyQA a, SQDPRCDEF1 b
WHERE a.qaamon = ' + #datemth + ' AND a.qaaday = ' + #DATEDAY + ' AND a.plantid = "1"'
GROUP BY b.procno, b.proseq, a.orderno, a.ingotno, a.theopcs, a.cwacc, a.pwacc, a.pwout,
a.COprocyld, a.COprodyld, a.plantid, a.prodline

Big ugly cursor

I'm populating a table of about 15 columns from a table of about 1000 columns. I need to grab the time from the big table. That time is broken up into minutes and hours [rn-min] and [rn-hr] and I need them in an am/pm format in the new table. The table is populated by an outside company so I can't really change much about it, I did get them to put in a transferred column for me to check. It's big and slow and I only need a few columns and there is a lot of duplicate/similar rows. In any case I'm making the smaller table from the bigger table. I wrote a cursor, its slow and I was wondering if there was a better way to do it. I can't just use a simple insert(select columns) because I want to change the way the time and date are stored. Thanks, any help or advice is appreciated
declare data CURSOR READ_ONLY FORWARD_ONLY
for
select [raID],
(otherfields),
CAST([RA-rent-mm] as varchar(2)) + '/' + CAST([RA-rent-dd] as varchar(2)) + '/' +
CAST([RA-Rent-CC] as varchar(2)) + CAST([RA-RENT-YY] as varchar(2)) [Date_Out],
CAST([RA-Rtrn-mm] as varchar(2)) + '/' + CAST([RA-Rtrn-dd] as varchar(2)) +
'/' + CAST([RA-Rtrn-CC] as varchar(2)) + CAST([RA-Rtrn-YY] as varchar(2)) [Date_In],
CAST([RA-RENTAL-HOURS] as varchar(2)),
CAST([RA-RENTAL-Minutes] as varchar(2)),
CAST([RA-RTRN-HOURS] as varchar(2)),
CAST([RA-RTRN-MINUTES] as varchar(2)),
(other fields)
from table_name
where Transfered is null
and [RA-rtrn-mm] != 0 --this keeps me from getting the duplicate/similar rows, once this doesn't equal 0 there aren't anymore rows so I just grab this one
declare #sql as varchar(max)
declare #raID int;
(other fields),
declare #rentDate varchar(8);
declare #rtrnDate varchar(8);
declare #rentHours varchar(2);
declare #rentMinutes varchar(2);
declare #rtrnHours varchar(2);
declare #rtrnMinutes varchar(2);
(other fields)
open data
fetch next from data into
#raID,
(other fields),
#rentDate ,
#rtrnDate ,
#rentHours ,
#rentMinutes ,
#rtrnHours ,
#rtrnMinutes ,
(other fields),
while ##FETCH_STATUS = 0
begin
set #rentMinutes = left('0' + #rentMinutes,2);--padding with 0 if minutes is 1-9
set #rtrnMinutes = left('0' + #rtrnMinutes,2);
--turning the varchar times into a time then back to varchar with correct am/pm notation
declare #rentT time = #rentHours + ':' + #rentMinutes;
declare #rtnT time = #rtrnHours + ':' + #rtrnMinutes;
declare #rentTime varchar(7) = convert(varchar(15),#rentT, 100);
declare #returnTime varchar(7) = convert(varchar(15),#rtnT, 100);
--print #rentTime;
set #sql = 'INSERT other_tbl_name(raID, (other fields), Date_Out, Date_In, Time_Out, Time_In, (other fields))
values ('+cast(#raID as varchar(max))+', (other fields),'''+#rentDate+''',
'''+#rtrnDate+''', '''+#rentTime+''', '''+#returnTime+''',
(other fields))';
--exec(#sql)
print #sql
--need a way to make sure the insert worked before updating
--need to update transferred to keep from updating the same info
declare #update as varchar(max) = '
UPDATE Capture.icokc_data
SET Transfered = 1
WHERE [raID] = '+cast(#raID as varchar(10))
--exec(#update)
--print #update
fetch next from data into
#raID,
(other fields)
#rentDate ,
#rtrnDate ,
#rentHours ,
#rentMinutes ,
#rtrnHours ,
#rtrnMinutes ,
(other fields)
end
close data;
deallocate data;
Why dont you bulk insert it, and transform the dates and times in the select?
Something like this:
INSERT other_tbl_name(raID, (other fields), Date_Out, Date_In, Time_Out, Time_In, (other fields))
select
[raID],
(otherfields),
CAST([RA-rent-mm] as varchar(2)) + '/' + CAST([RA-rent-dd] as varchar(2)) + '/' + CAST([RA-Rent-CC] as varchar(2)) + CAST([RA-RENT-YY] as varchar(2)) [Date_Out],
CAST([RA-Rtrn-mm] as varchar(2)) + '/' + CAST([RA-Rtrn-dd] as varchar(2)) + '/' + CAST([RA-Rtrn-CC] as varchar(2)) + CAST([RA-Rtrn-YY] as varchar(2)) [Date_In],
CONVERT(varchar(15),DATEADD(minute, [RA-RENTAL-Minutes], DATEADD(hour, [RA-RENTAL-HOURS], '00:00')), 100) as [Time_out],
CONVERT(varchar(15),DATEADD(minute, [RA-RTRN-MINUTES], DATEADD(hour, [RA-RTRN-HOURS], '00:00')), 100) as [Time_in],
(other fields)
from table_name
where Transfered is null
and [RA-rtrn-mm] != 0
UPDATE Capture.icokc_data
SET Transfered = 1
WHERE [raID] IN
(
select
[raID]
from table_name
where Transfered is null
-- and [RA-rtrn-mm] != 0 -- not sure about this one
)
As it's a direct conversion, i.e. one record in and one record out, I don't really see any reason why it couldn't be done with a single insert query.
Anyhow, don't create queries dynamically. The dynamic queries will be parsed and planned for each iteration, which is most likely the reason for most of the performance problems.
For example, instead of:
declare #update as varchar(max) = '
UPDATE Capture.icokc_data
SET Transfered = 1
WHERE [raID] = '+cast(#raID as varchar(10))
exec(#update)
just do:
UPDATE Capture.icokc_data
SET Transfered = 1
WHERE [raID] = #raID