I've got three tables; tblProducts and tblOption and tblOptionValue. (T-SQL)
I get all possible combinations of my product using the this query:
DECLARE #ProductId INT, #Query NVARCHAR(MAX), #ProductOptionGroupId INT
SET #ProductId = 69
SET #Query = ''
DECLARE CC CURSOR FOR
SELECT DISTINCT OptionID
FROM tblOption
WHERE ProductId = #ProductId
OPEN CC
FETCH NEXT FROM CC INTO #ProductOptionGroupId
WHILE ##FETCH_STATUS = 0
BEGIN
SET #Query = #Query + '(SELECT DISTINCT tblOptionValue.Name FROM tblOptionValue INNER JOIN tblOption on tblOptionValue.OptionID = tblOption.OptionID WHERE tblOptionValue.OptionId='+CAST(#ProductOptionGroupId AS VARCHAR)+'AND tblOption.ProductId='+CAST(#ProductId AS VARCHAR)+
+') AS Table' + CAST(#ProductOptionGroupId AS VARCHAR)+' CROSS JOIN '
FETCH NEXT FROM CC INTO #ProductOptionGroupId
END
CLOSE CC
DEALLOCATE CC
SET #Query = 'SELECT * FROM ' + LEFT(#Query,LEN(#Query)-10)
PRINT #Query
EXEC sp_executesql #Query
Found here thanks to #Lamak
I've adapted it to my database but I need to:
A) Find a way to pull all the data back in one column instead of multiple columns
B) Name the tblOptionValue.Name column the same as the associated tblOption.Name field
Any thoughts on how I might achieve the above?
Many thanks
Update: I managed to achieve my goals, using the following query:
DECLARE #ProductId INT, #Query NVARCHAR(MAX), #ProductOptionGroupId INT, #cName VARCHAR(300)
SET #ProductId = 70
SET #Query = ''
DECLARE CC CURSOR FOR
SELECT DISTINCT OptionID
FROM tblOption
WHERE ProductId = #ProductId
OPEN CC
FETCH NEXT FROM CC INTO #ProductOptionGroupId
WHILE ##FETCH_STATUS = 0
BEGIN
set #cName = (SELECT Name FROM tblOption WHERE OptionID=#ProductOptionGroupId)
SET #Query = #Query + '(SELECT DISTINCT tblOptionValue.Name as '+#cName+' FROM tblOptionValue INNER JOIN tblOption on tblOptionValue.OptionID = tblOption.OptionID INNER JOIN tblProduct on tblOption.ProductID=tblProduct.ProductID WHERE tblOptionValue.OptionId='+CAST(#ProductOptionGroupId AS VARCHAR)+'AND tblOption.ProductId='+CAST(#ProductId AS VARCHAR)+
+') AS Table' + CAST(#ProductOptionGroupId AS VARCHAR)+' CROSS JOIN '
FETCH NEXT FROM CC INTO #ProductOptionGroupId
END
CLOSE CC
DEALLOCATE CC
SET #Query = 'SELECT t2.*, t1.* FROM (SELECT * FROM ' + LEFT(#Query,LEN(#Query)-10)
SET #Query = #Query + ') as t1,
(SELECT * FROM tblProduct WHERE ProductID=70) as t2'
PRINT #Query
EXEC sp_executesql #Query
Put the user's solution into an answer.
DECLARE #ProductId INT, #Query NVARCHAR(MAX), #ProductOptionGroupId INT, #cName VARCHAR(300)
SET #ProductId = 70
SET #Query = ''
DECLARE CC CURSOR FOR
SELECT DISTINCT OptionID
FROM tblOption
WHERE ProductId = #ProductId
OPEN CC
FETCH NEXT FROM CC INTO #ProductOptionGroupId
WHILE ##FETCH_STATUS = 0
BEGIN
set #cName = (SELECT Name FROM tblOption WHERE OptionID=#ProductOptionGroupId)
SET #Query = #Query + '(SELECT DISTINCT tblOptionValue.Name as '+#cName+' FROM tblOptionValue INNER JOIN tblOption on tblOptionValue.OptionID = tblOption.OptionID INNER JOIN tblProduct on tblOption.ProductID=tblProduct.ProductID WHERE tblOptionValue.OptionId='+CAST(#ProductOptionGroupId AS VARCHAR)+'AND tblOption.ProductId='+CAST(#ProductId AS VARCHAR)+
+') AS Table' + CAST(#ProductOptionGroupId AS VARCHAR)+' CROSS JOIN '
FETCH NEXT FROM CC INTO #ProductOptionGroupId
END
CLOSE CC
DEALLOCATE CC
SET #Query = 'SELECT t2.*, t1.* FROM (SELECT * FROM ' + LEFT(#Query,LEN(#Query)-10)
SET #Query = #Query + ') as t1,
(SELECT * FROM tblProduct WHERE ProductID=70) as t2'
PRINT #Query
EXEC sp_executesql #Query
Related
I have been using a standard block of TSQL for auditing of various tables for some time now. However I now have a problem when running the trigger on a new table: "Error converting data type varchar to numeric". This occurs when running the EXEC (#sql) line. I've determined that the code for #sql is:
insert Audit_AppointmentsWS
(Type,
TableName,
PK,
FieldName,
OldValue,
NewValue,
UpdateDate,
UserName)
SELECT 'U',
'AppointmentsWorkshop',
+convert(varchar(100), coalesce(i.UniqueID,d.UniqueID)),
'[JobHours]',
convert(varchar(1000),d.[JobHours]),
convert(varchar(1000),i.[JobHours]),
'20220816 12:32:43:410',
'DELLXPS\ian'
from #ins i full outer join #del d on i.UniqueID = d.UniqueID where ISNULL(i.JobHours],'') <> ISNULL(d.[JobHours],'')
I've tried deleting the trigger & the audit table and then recreating them but no joy. I've also tried copying an existing trigger and just changing the table details but I still get the same error. I'm completely stumped on this and would appreciate some feedback. Many thanks in advance!
Here is the trigger:
/****** Object: Trigger [dbo].[tr_AppointmentsWS] Script Date: 16/08/2022 12:02:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create TRIGGER [dbo].[tr_AppointmentsWS] ON [dbo].AppointmentsWorkshop FOR UPDATE, DELETE
AS
DECLARE #bit INT ,
#field INT ,
#maxfield INT ,
#char INT ,
#fieldname VARCHAR(128) ,
#TableName VARCHAR(128) ,
#AuditTable VARCHAR(128) ,
#PKCols VARCHAR(MAX) ,
#sql VARCHAR(2000),
#UpdateDate VARCHAR(21) ,
#UserName VARCHAR(128) ,
#Type CHAR(1) ,
#PKSelect VARCHAR(MAX)
--Changes required:
-- 1. Change the name of the trigger and the table, above
-- 2. Change #TableName to match the table to be audited
-- 3. Change the #AuditTable to the table holding the changes
SELECT #TableName = 'AppointmentsWorkshop'
SELECT #AuditTable = 'Audit_AppointmentsWS'
-- date and user
SELECT #UserName = SYSTEM_USER ,
#UpdateDate = CONVERT(VARCHAR(8), GETDATE(), 112) + ' ' + CONVERT(VARCHAR(12), GETDATE(), 114)
-- Action
IF EXISTS (SELECT * FROM inserted)
IF EXISTS (SELECT * FROM deleted)
SELECT #Type = 'U'
ELSE
SELECT #Type = 'I'
ELSE
SELECT #Type = 'D'
-- get list of columns
SELECT * INTO #ins FROM inserted
SELECT * INTO #del FROM deleted
-- Get primary key columns for full outer join
SELECT #PKCols = COALESCE(#PKCols + ' and', ' on') + ' i.' + c.COLUMN_NAME + ' = d.' + c.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk, INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = #TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
-- Get primary key select for insert
SELECT #PKSelect = COALESCE(#PKSelect+'+','') + '+convert(varchar(100), coalesce(i.' + COLUMN_NAME +',d.' + COLUMN_NAME + '))'
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk, INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = #TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
IF #PKCols IS NULL
BEGIN
RAISERROR('no PK on table %s', 16, -1, #TableName)
RETURN
END
SELECT #field = 0, #maxfield = MAX(COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + #Tablename),COLUMN_NAME, 'ColumnID'))
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = #TableName
WHILE #field < #maxfield
BEGIN
SELECT #field = MIN(COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + #Tablename),COLUMN_NAME, 'ColumnID'))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #TableName
AND COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + #Tablename),COLUMN_NAME, 'ColumnID') > #field
SELECT #bit = (#field - 1 )% 8 + 1
SELECT #bit = POWER(2,#bit - 1)
SELECT #char = ((#field - 1) / 8) + 1
IF SUBSTRING(COLUMNS_UPDATED(),#char, 1) & #bit > 0 OR #Type IN ('I','D')
BEGIN
SELECT #fieldname = COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #TableName
AND COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + #Tablename),COLUMN_NAME, 'ColumnID') = #field
SELECT #sql = 'insert ' + #AuditTable + '
(Type,
TableName,
PK,
FieldName,
OldValue,
NewValue,
UpdateDate,
UserName)
SELECT ''' + #Type + ''','''
+ #TableName + ''',' + #PKSelect
+ ',''[' + #fieldname + ']'''
+ ',convert(varchar(1000),d.[' + #fieldname + '])'
+ ',convert(varchar(1000),i.[' + #fieldname + '])'
+ ',''' + #UpdateDate + ''''
+ ',''' + #UserName + ''''
+ ' from #ins i full outer join #del d'
+ #PKCols
+ ' where ISNULL(i.[' + #fieldname + '],'''') <> ISNULL(d.[' + #fieldname + '],'''')' --Skip identical values and excludes NULLS vs empty strings
EXEC (#sql)
END
END
Well I finally figured it out. The error is being generated with columns of data type 'decimal' and it is down to the ISNULL section of the last SELECT. I've fixed it by checking for the decimal type and then using the following code (which included a zero rather than an empty sting):
+ ' where ISNULL(i.[' + #fieldname + '],''0'') <> ISNULL(d.[' + #fieldname + '],''0'')' --Skip identical values and excludes NULLS vs empty strings
Context: I am exploring a new database (in MS SQL server), and I want to know for each table, all columns that have null values.
I.e. result would look something like this:
table column nulls
Tbl1 Col1 8
I have found this code here on stackoverflow, that makes a table of table-columnnames - without the WHERE statement which is my addition.
I tried to filter for nulls in WHERE statement, but then the table ends up empty, and I see why - i am checking if the col name is actually null, and not its contents. But can't figure out how to proceed.
select schema_name(tab.schema_id) as schema_name,
tab.name as table_name,
col.name as column_name
from sys.tables as tab
inner join sys.columns as col
on tab.object_id = col.object_id
left join sys.types as t
on col.user_type_id = t.user_type_id
-- in this where statement, I am trying to filter for nulls, but i get an empty result. and i know there are nulls
where col.name is null
order by schema_name, table_name, column_id
I also tried this (see 4th line):
select schema_name(tab.schema_id) as schema_name,
tab.name as table_name,
col.name as column_name
,(select count(*) from tab.name where col.name is null) as countnulls
from sys.tables as tab
inner join sys.columns as col
on tab.object_id = col.object_id
left join sys.types as t
on col.user_type_id = t.user_type_id
order by schema_name, table_name, column_id
the last one returns an error "Invalid object name 'tab.name'."
column name can't be null but if you mean nullable column (column that accept null value) that has null value at least so you can use following statement:
declare #schema varchar(255), #table varchar(255), #col varchar(255), #cmd varchar(max)
DECLARE getinfo cursor for
SELECT schema_name(tab.schema_id) as schema_name,tab.name , col.name from sys.tables as tab
inner join sys.columns as col on tab.object_id = col.object_id
where col.is_nullable =1
order by schema_name(tab.schema_id),tab.name,col.name
OPEN getinfo
FETCH NEXT FROM getinfo into #schema,#table,#col
WHILE ##FETCH_STATUS = 0
BEGIN
set #schema = QUOTENAME(#schema)
set #table = QUOTENAME(#table)
set #col = QUOTENAME(#col)
SELECT #cmd = 'IF EXISTS (SELECT 1 FROM '+ #schema +'.'+ #table +' WHERE ' + #col + ' IS NULL) BEGIN SELECT '''+#schema+''' as schemaName, '''+#table+''' as tablename, '''+#col+''' as columnName, * FROM '+ #schema +'.'+ #table +' WHERE ' + #col + ' IS NULL end'
EXEC(#cmd)
FETCH NEXT FROM getinfo into #schema,#table,#col
END
CLOSE getinfo
DEALLOCATE getinfo
that use cursor on all nullable columns in every table in the Database then check if this column has at least one null value if yes will select schema Name, table name, column name and all records that has null value in this column
but if you want to get only count of nulls you can use the following statement:
declare #schema varchar(255), #table varchar(255), #col varchar(255), #cmd varchar(max)
DECLARE getinfo cursor for
SELECT schema_name(tab.schema_id) as schema_name,tab.name , col.name from sys.tables as tab
inner join sys.columns as col on tab.object_id = col.object_id
where col.is_nullable =1
order by schema_name(tab.schema_id),tab.name,col.name
OPEN getinfo
FETCH NEXT FROM getinfo into #schema,#table,#col
WHILE ##FETCH_STATUS = 0
BEGIN
set #schema = QUOTENAME(#schema)
set #table = QUOTENAME(#table)
set #col = QUOTENAME(#col)
SELECT #cmd = 'IF EXISTS (SELECT 1 FROM '+ #schema +'.'+ #table +' WHERE ' + #col + ' IS NULL) BEGIN SELECT '''+#schema+''' as schemaName, '''+#table+''' as tablename, '''+#col+''' as columnName, count(*) as nulls FROM '+ #schema +'.'+ #table +' WHERE ' + #col + ' IS NULL end'
EXEC(#cmd)
FETCH NEXT FROM getinfo into #schema,#table,#col
END
that use cursor on all nullable columns in every table in the Database then check if this column has at least one null value if yes will select schema Name, table name, column name and count all records that has null value in this column
I am attempting to use dynamic sql to select a value based on a field. I have a table of field references I am using for the column names. What I am having troubles with is of course the dynamic sql. My return result is (SELECT ecoa_code FROM CRA_METRO2_BASE WHERE id = 568470) for example. But I really want it to run that select statement. Executing only returns the last row.
DECLARE #BaseCol VARCHAR(250)
SELECT
#BaseCol = '(SELECT ' + FR_base.field_name + ' FROM CRA_METRO2_BASE WHERE id = ' + CONVERT(VARCHAR(15), B.id) + ')'
FROM CRA_INNOVIS_AUDIT_ERROR_FIELDS E
LEFT JOIN CRA_METRO2_BASE B
ON B.id = E.base_id
LEFT JOIN CRA_METRO2_FIELD_REF FR_base
ON FR_base.id = E.base_field_ref
WHERE E.audit_id = #audit_id
EXEC(#BaseCol)
I am not sure I understand your premises correctly and without a mock-up...; so please take this answer with a grain of salt:)
DECLARE #sqlstring VARCHAR(MAX)
SELECT #sqlstring = 'SELECT ' + a.column_name + ' FROM ' + a.[Schema] + '.' + a.table_name
from (
SELECT TOP 1 T.object_id,OBJECT_SCHEMA_NAME(T.[object_id],DB_ID()) AS [Schema],
T.[name] AS [table_name], AC.[name] AS [column_name]
--,TY.[name] AS system_data_type
, AC.[max_length],
AC.[precision], AC.[scale], AC.[is_nullable], AC.[is_ansi_padded]
,AC.column_id
FROM sys.tables AS T
INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id]
) a
SELECT #sqlstring
EXEC(#sqlstring)
So I used my above query and now I am using a CTE to build my basic result list. And in my cte I create update statements which then are all put into a temp table.
I extract the update statements and execute them on the temp table. And walla, I have my results!
IF(OBJECT_ID('tempdb..#Temp') IS NOT NULL)
BEGIN
DROP TABLE #Temp
END
CREATE TABLE #Temp
(
usb_data VARCHAR(500),
cra_data VARCHAR(500)
);
WITH ErrorFieldsCTE(id, field, usb_data, cra_data, AUD, SOR, acceptable_variance, is_variance_known, is_reviewed)
AS(
SELECT
+ 'UPDATE #TEMP SET usb_data = (SELECT ' + FR_base.field_name +' FROM CRA_METRO2_BASE WHERE id = '+ CONVERT(VARCHAR(25), B.id) +' ) WHERE id = ' + CONVERT(VARCHAR(15), E.id) + ' ' [usb_data],
+ 'UPDATE #TEMP SET cra_data = (SELECT ' + FR_audit.field_name +' FROM CRA_INNOVIS_INBOUND_AUDIT_INFORMATION WHERE id = '+ CONVERT(VARCHAR(25), A.id) +') WHERE id = ' + CONVERT(VARCHAR(15), E.id) + ' ' [cra_data]
FROM CRA_INNOVIS_AUDIT_ERROR_FIELDS E
LEFT JOIN CRA_METRO2_BASE B
ON B.id = E.base_id
LEFT JOIN CRA_INNOVIS_INBOUND_AUDIT_INFORMATION A
ON A.id = E.audit_id
LEFT JOIN CRA_METRO2_FIELD_REF FR_audit
ON FR_audit.id = E.audit_field_ref
LEFT JOIN CRA_METRO2_FIELD_REF FR_base
ON FR_base.id = E.base_field_ref
WHERE E.audit_id = #audit_id
)
INSERT INTO #Temp
SELECT
id, field, usb_data, cra_data, AUD, SOR, acceptable_variance, is_variance_known, is_reviewed
FROM ErrorFieldsCTE
SELECT -- extract query
#usb_data += usb_data + '',
#cra_data += cra_data + ''
FROM #Temp
EXEC(#usb_data) -- updating temp table, selects usb-data
EXEC(#cra_data) -- updating temp table, selects cra-data
SELECT -- return to web
id, field, usb_data, cra_data, AUD, SOR, acceptable_variance, is_variance_known, is_reviewed
FROM #Temp
IF(OBJECT_ID('tempdb..#Temp') IS NOT NULL)
Begin
Drop Table #Temp
End
I am currently using the following code within SQL Server 2005 to obtain data on orphaned user SID's, this works well but I really need to get information on role memberships for each orphaned userSID, is this possible and if so, how can I write a query for this?
DECLARE cur CURSOR FAST_FORWARD FOR
SELECT name FROM sys.databases
WHERE database_id > 4
OPEN cur
DECLARE #SQL NVARCHAR(MAX), #DBName SYSNAME
DECLARE #Results TABLE (DBName SYSNAME, UserName SYSNAME, UserSID VARBINARY(MAX))
FETCH NEXT FROM cur into #DBName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SQL = 'USE ' + #DBName + ';SELECT ''' + #DBName + ''' AS DBName,
UserName = name, UserSID = sid from sysusers
WHERE issqluser = 1 AND
(sid IS NOT NULL AND sid <> 0x0) AND
(LEN(sid) <= 16) AND SUSER_SNAME(sid) IS NULL'
INSERT INTO #Results
EXEC(#SQL)
FETCH NEXT FROM cur into #DBName
END
CLOSE cur
DEALLOCATE cur
SELECT * FROM #Results
Thanks!
Thanks for the replies, I've created the below query based on the info given so far, this looks like it gives what I need?
select u.uid, u.name, u.sid, rm.role_principal_id as 'Role ID', dp1.name as 'Role'
from sys.sysusers u
left join sys.syslogins l on UPPER(u.sid) = UPPER(l.sid)
inner join sys.database_role_members rm on rm.member_principal_id = u.uid
left join sys.database_principals dp on dp.principal_id = rm.member_principal_id
left join sys.database_principals dp1 on dp1.principal_id = rm.role_principal_id
where u.uid > 4 and u.issqlrole = 0
and issqluser = 1
and l.name is null
order by u.name
It selects user membership.
select case when SUSER_SNAME( dp.sid ) is null then dp.name else SUSER_SNAME( dp.sid ) end 'dbUser',
dp2.name 'dbRole', dp.type_desc uDesc
from sys.database_principals dp left join sys.database_role_members dr
on dr.member_principal_id = dp.principal_id
left join sys.database_principals dp2 on dr.role_principal_id = dp2.principal_id
where dp.type_desc <> 'DATABASE_ROLE'
and case when SUSER_SNAME( dp.sid ) is null then dp.name else SUSER_SNAME( dp.sid ) end
not in ('sys', 'INFORMATION_SCHEMA', 'guest')
order by 1
I have noticed that your cursor selects orphaned SQL logins only. Do you need orphaned Windows logins? If yes, then check following query.
select u.name, *
from sys.sysusers u left join sys.syslogins l on UPPER(u.sid) = UPPER(l.sid)
where u.uid > 4 and u.issqlrole = 0
and l.name is null
order by u.name
I have a SP that is supposed to compare 2 temp tables generated from a function to another table. My issue is that instead of stepping through each temp table it goes through both at the same time. I am not sure how to write the code to step through each table one at a time to get the desired results.
DROP PROCEDURE uspJudgments;
GO
CREATE PROCEDURE uspJudgments
#fullName varchar(100), #fullName1 varchar(100)
AS
BEGIN
SELECT *
INTO #tmpFullname
FROM dbo.DelimitedSplit8K(#fullName, ',')
SELECT *
INTO #tmpFullname1
FROM dbo.DelimitedSplit8K(#fullName1, ',')
SELECT *
FROM #tmpFullName
SELECT *
FROM #tmpFullName1
DECLARE #MaxRownum int
SET #MaxRownum = (SELECT MAX(ItemNumber) FROM #tmpFullname)
DECLARE #Iter int
SET #Iter = (SELECT MIN(ItemNumber) FROM #tmpFullname)
DECLARE #MaxRownum1 int
SET #MaxRownum1 = (SELECT MAX(ItemNumber) FROM #tmpFullname1)
DECLARE #Iter1 int
SET #Iter1 = (SELECT MIN(ItemNumber) FROM #tmpFullname1)
DECLARE #Name varchar(25)
DECLARE #Name1 varchar(25)
WHILE #Iter <= #MaxRownum AND #iter1 <= #Maxrownum1
BEGIN
SET #Name = (SELECT Item FROM #tmpFullname WHERE ItemNumber = #Iter)
SET #Name1 = (SELECT Item FROM #tmpFullname1 WHERE ItemNumber = #Iter1)
SELECT *
--INTO #tmpDefSelect
FROM defendants_ALL
WHERE combined_name LIKE '%' + #Name + '%' AND combined_name LIKE '%' + #Name1 + '%';
SET #Iter = #Iter + 1
SET #Iter1 = #Iter1 + 1
END
END
DROP TABLE #tmpFullname
DROP TABLE #tmpFullname1
EXEC uspJudgments #fullName = 'grein,smit', #fullName1 = 'joh,jon,j.'
I need to get ALL results for grein -- joh, jon, j. AND smit, joh, jon, j.
Currently the above code only returns grein joh AND smit, jon.. In our database that returns no results for the first combination and 38 results for jonathon smith and jon smith. How do I properly step through each temp table to get the desired results?
You only get the two combinations grein joh and smith jon because of the way you are iterating through #Iter and #iter1. You increment both of them at the same time. You need a nested loop like this:
declare #start_val integer = #iter1
while #Iter <= MaxRownum
begin
set #iter1 = #start_val
while #iter1 <= #Maxrownum1
begin
set #Name = ...
set #Name1 = ...
...
set #iter1 = #iter1 + 1
end
set #Iter = #Iter + 1
end
But I don't think you even need the WHILE loops:
select d.*
from defendants_ALL, #tmpFullname t1, #tmpFullname1 t2
where d.combined_name = t1.Item + ' ' + t2.Item
Or (if you need to still use LIKE):
select d.*
from defendants_ALL, #tmpFullname t1, #tmpFullname1 t2
where d.combined_name like '%' + t1.Item + '%'
and d.combined_name like '%' + t2.Item + '%'
(All SQL is untested...)