Is it possible to use a parameter for LIKE / NOT LIKE - tsql

I am attempting to pass parameters for LIKE / NOT LIKE and the % signs to make a dynamic query that runs based on what is passed from the application. I get an error though as TSQL is confused about the parameter for like/not like as its not Boolean. Is it possible to do it this way or am I going to have to write multiple if statements to check to see what parameters are being passed.
#fullName varchar(100), #SrchCriteria1 varchar(15), #SrchCriteria2 varchar(15),
#fullName1 varchar(100), #SrchCriteria3 varchar(15), #SrchCriteria4 varchar(15),
#fullName2 varchar(100), #SrchCriteria5 varchar(15), #SrchCriteria6 varchar(15),
#qualifer varchar(10), #qualifer1 varchar(10), #qualifer2 varchar(10)
SELECT d.*
FROM defendants_ALL d, #tmpFullname t1, #tmpFullname1 t2, #tmpFullname2 t3
WHERE d.combined_name + #qualifer + #SrchCriteria1 + t1.Item + #SrchCriteria2
and d.combined_name + #qualifer + #SrchCriteria3 + t2.Item + #SrchCriteria4
and d.combined_name + #qualifer + #SrchCriteria5 + t3.Item + #SrchCriteria6
EXEC uspJudgments #qualifier = 'LIKE', #qualifier1 = 'LIKE', #qualifier = 'NOT LIKE', #fullName = 'johns', #fullName1 = 'jim,j.', #SrchCriteria1 = '%', #SrchCriteria2 = '%', #SrchCriteria3 = '%', #SrchCriteria4 = '%', #fullName2 = 'johnson', #SrchCriteria5 = '%', #SrchCriteria6 = '%'
So that should return all combinations of jim johns and j. johns but will not include jim johnson and j. johnson. I know that is a rare combination but I couldn't think of a better one ATM that is more common.
Dynamic SQL:
DECLARE #Query NVarChar(1024)
SET #Query = 'SELECT d.* FROM defendants_ALL d, #tmpFullname t1, #tmpFullname1 t2, #tmpFullname2 t3' +
'WHERE d.combined_name' + #qualifier + #SrchCriteria1 + 't1.Item' + #SrchCriteria2 +
' and d.combined_name' + #qualifier + #SrchCriteria3 + 't2.Item' + #SrchCriteria4 +
' and d.combined_name' + #qualifier + #SrchCriteria5 + 't3.Item' + #SrchCriteria6

LIKE accepts an expression for the pattern, e.g. d.combined_name LIKE #SrchCriteria.
You are attempting to assemble a dynamic query. To do so, you need to create the entire query in a string and then use EXECUTE:
declare #Query as NVarChar(1024) = 'SELECT d.* FROM ...' +
'WHERE d.combined_name ' + #qualifer + #SrchCriteria1 + t1.Item + #SrchCriteria2 +
'...'
The statement may be assembled in several steps before being passed to EXECUTE.

Related

Error converting data type varchar to numeric in standard audit trigger

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

Sending email from SSRS repor 2008

I have the below supplier data in SSRS 2008 report.
ID Name Details Email
1 abc d1 rob.b#gmail.com
2 def d2 pat#gmail.com
3 ghi d3 golf#gmail.com
4 dft d4 rob.b#gmail.com
I need to send the relevant details to each email id. For example, in the data above, I need to send the entire record of ID 1 and 4 to rob.b#gmail.com.
Is there any way to send just the relevant details to the emails given in the report. Could someone please advise.
Yes - you can use a Data Driven Subscription to do this in SSRS - if you have the Enterprise version of SQL Server.
If you do not have the Enterprise version, you can still do this with a little bit more effort using a scheduled Stored Procedure to emulate the data driven subscription.
Either way, you would have a report that works with a parameter to identify a single record. Then the separate data driven part would have a different query that gets a list of IDs that you need for the report along with the e-mail address to send it to. The data driven part will then generate a separate report for each of the ID parameter that you created in the report and then send them to the address.
Data Driven Subscription properties:
Unfortunately, both methods are too big of a topic to be covered in an answer.
MSDN - Data Driven Subscriptions
MSSQLTips.com - simulate-reporting-services-data-driven-subscriptions
Here's a SP that I made to generate multiple e-mail:
ALTER PROCEDURE [dbo].[RECORD_REVIEW_GENERATION]
AS
DECLARE #SUBSCRIPTION_ID AS VARCHAR(100) = (SELECT SETTING_VALUE FROM WORKING_STORAGE.dbo.SETTINGS WHERE SETTING_NAME = 'REVIEW_SUBSCRIPTION')
DECLARE #SUBJECT VARCHAR(200)
DECLARE #COMMENT VARCHAR(500)
DECLARE #REVIEW_ID VARCHAR(50)
DECLARE #EXTENSION_SETTINGS XML
DECLARE #PARAMETERS XML
DECLARE #RECORD_ID AS INT
DECLARE #MAX_RECORD_ID AS INT
DECLARE #END_DATE AS DATE = GETDATE() - DATEPART(WEEKDAY, GETDATE()) --PREVIOUS SUNDAY
DECLARE #START_DATE AS DATE = DATEADD(DAY, -6, #END_DATE) --PREVIOUS MONDAY
DECLARE #DATE VARCHAR(500) = CONVERT(VARCHAR(8), #END_DATE, 112)
SELECT #EXTENSION_SETTINGS = ExtensionSettings, #PARAMETERS = [Parameters]
FROM ReportServer.dbo.Subscriptions
WHERE SubscriptionID = #SUBSCRIPTION_ID;
IF OBJECT_ID('tempdb..#REVIEWS') IS NOT NULL DROP TABLE #REVIEWS
CREATE TABLE #REVIEWS(ReviewID VARCHAR(50), ProviderName VARCHAR(250), SiteIDNo VARCHAR(20),
ReviewDate VARCHAR(12), UserName VARCHAR(250), VisitPurpose VARCHAR(250),
NoOfPhysicians INT, NoOfRecords INT, RECORD_ID INT IDENTITY(1,1)
)
INSERT INTO #REVIEWS(ReviewID, ProviderName, SiteIDNo, ReviewDate, UserName, VisitPurpose, NoOfPhysicians, NoOfRecords)
SELECT ReviewID, ProviderName, SiteIDNo, ReviewDate, UserFirstName + ' ' + UserLastName AS UserName, VisitPurpose, NoOfPhysicians, NoOfRecords
FROM KHSSQLODSPRD.QI_SITE_REVIEW.dbo.RecordHeader
WHERE ExportDate BETWEEN #START_DATE AND #END_DATE
ORDER BY ReviewDate
SET #RECORD_ID = 1
SET #MAX_RECORD_ID = (SELECT ISNULL(MAX(RECORD_ID), 0) FROM #REVIEWS)
WHILE #RECORD_ID <= #MAX_RECORD_ID
BEGIN
SELECT #REVIEW_ID = ReviewID,
#SUBJECT = 'Review - ' + ProviderName,
#COMMENT = CAST(#RECORD_ID AS VARCHAR(10)) + ' of ' + CAST(#MAX_RECORD_ID AS VARCHAR(10))
+ ' Review Surveys for the week ending ' + RTRIM(CONVERT(VARCHAR(12), #END_DATE, 110)) + '.'
+ CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10) + ProviderName + ' [' + SiteIDNo + '] - Reviewed ' + RTRIM(CONVERT(VARCHAR(12), ReviewDate, 110))
+ '. Review ID ' + ReviewID
+ CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10) + VisitPurpose + ' visit for ' + CAST(CAST(NoOfPhysicians AS INT) AS VARCHAR(20)) + ' physicians with '
+ CAST(CAST(NoOfRecords AS INT) AS VARCHAR(20)) + ' records by ' + UserName + '.'
FROM #REVIEWS
WHERE RECORD_ID = #RECORD_ID
SET #REVIEW_ID = LOWER(#REVIEW_ID)
--SET EXTENSION OPTIONS
SET #EXTENSION_SETTINGS.modify('replace value of (/ParameterValues/ParameterValue[Name="Subject"]/Value/text())[1] with sql:variable("#SUBJECT")');
SET #EXTENSION_SETTINGS.modify('replace value of (/ParameterValues/ParameterValue[Name="Comment"]/Value/text())[1] with sql:variable("#COMMENT")');
--SET REPORT PARAMETERS
SET #PARAMETERS.modify('replace value of (/ParameterValues/ParameterValue[Name="SITE_ID"]/Value/text())[1] with sql:variable("#REVIEW_ID")');
--UPDATE SUBSCRIPTION PARAMETERS
UPDATE dbo.Subscriptions
SET ExtensionSettings = CAST(#EXTENSION_SETTINGS AS VARCHAR(8000)),
[Parameters] = CAST(#PARAMETERS AS VARCHAR(8000))
WHERE SubscriptionID = #SUBSCRIPTION_ID
EXEC dbo.AddEvent #EventType = 'TimedSubscription', #EventData = #SUBSCRIPTION_ID;
--WAIT WHILE REPORT GENERATES
WAITFOR DELAY '00:00:03.000';
--IF REPORT IS STILL EXECUTING, WAIT SOME MORE
WHILE EXISTS (SELECT TOP 1 'X' FROM dbo.Event WHERE EventData = #SUBSCRIPTION_ID ) OR EXISTS (SELECT TOP 1 'X' FROM dbo.Notifications WHERE SubscriptionID = #SUBSCRIPTION_ID)
BEGIN
WAITFOR DELAY '00:00:01.000';
PRINT 'Waiting for subscription to finish'
END
SET #RECORD_ID = #RECORD_ID + 1
END --END OF LOOP
-- SET #FLAG = 1
You'd add the TO address the same way as the Comment is updated. The #Review_ID is passed to the report as a parameter.

Fields not showing in Crystal Reports

Hi I have the following dyanmic stored procedure which returns a normal result set at the end however crystal reports is not returning any fields along with it might anyone have an idea what is wrong.
When I run the proc in studio management it works fine. This is a report using the sap version of crystal in case that makes a difference.
I would normally output the results to excel and it runs correctly but for crystal its not allowing me to select any fields in the field explorer.
ALTER PROCEDURE [dbo].[ReportByDates]
#DateFrom date NULL,
#DateTo date NULL
AS
SET NOCOUNT ON;
DECLARE #DynamicColumnsDivision AS VARCHAR(max)
DECLARE #DynamicColumnsDivision2 AS VARCHAR(max)
DECLARE #DynamicColumnsDivisionTotal AS VARCHAR(max)
SELECT #DynamicColumnsDivision = COALESCE(#DynamicColumnsDivision + ', ', '')
+ 'ISNULL(' +Quotename(fieldname) + ',0) as ' + Quotename(fieldname)
FROM (
SELECT
DISTINCT
PrcCode + ' - ' + cc.PrcName as fieldname
FROM OPRC cc
WHERE Active = 'Y' AND CCTypeCode = 'Division'
) AS FieldList
SELECT #DynamicColumnsDivision2 = COALESCE(#DynamicColumnsDivision2 + ', ', '')
+ Quotename(fieldname)
FROM (
SELECT
DISTINCT
PrcCode + ' - ' + cc.PrcName as fieldname
FROM OPRC cc
WHERE Active = 'Y' AND CCTypeCode = 'Division'
) AS FieldList
SELECT #DynamicColumnsDivisionTotal = COALESCE(#DynamicColumnsDivisionTotal + '+', '')
+ 'ISNULL(' +Quotename(fieldname) + ',0)'
FROM (
SELECT
DISTINCT
PrcCode + ' - ' + cc.PrcName as fieldname
FROM OPRC cc
WHERE Active = 'Y' AND CCTypeCode = 'Division'
) AS FieldList
DECLARE #DynamicColumnsGQO AS VARCHAR(max)
DECLARE #DynamicColumnsGQO2 AS VARCHAR(max)
DECLARE #DynamicColumnsGQOTotal as VARCHAR(max)
SELECT #DynamicColumnsGQO = COALESCE(#DynamicColumnsGQO + ', ', '')
+ 'ISNULL(' +Quotename(fieldname) + ',0) as ' + Quotename(fieldname)
FROM (
SELECT
DISTINCT
PrcCode + ' - ' + cc.PrcName as fieldname
FROM OPRC cc
WHERE Active = 'Y' AND CCTypeCode = 'GQO'
) AS FieldList
SELECT #DynamicColumnsGQO2 = COALESCE(#DynamicColumnsGQO2 + ', ', '')
+ Quotename(fieldname)
FROM (
SELECT
DISTINCT
PrcCode + ' - ' + cc.PrcName as fieldname
FROM OPRC cc
WHERE Active = 'Y' AND CCTypeCode = 'GQO'
) AS FieldList
SELECT #DynamicColumnsGQOTotal = COALESCE(#DynamicColumnsGQOTotal + '+', '')
+ 'ISNULL(' +Quotename(fieldname) + ',0)'
FROM (
SELECT
DISTINCT
PrcCode + ' - ' + cc.PrcName as fieldname
FROM OPRC cc
WHERE Active = 'Y' AND CCTypeCode = 'GQO'
) AS FieldList
DECLARE #Query NVARCHAR(MAX)
SET #Query =
'SELECT Account, AcctName, ' + #DynamicColumnsDivision + ', ' + #DynamicColumnsDivisionTotal + ' as DivisionTotal , ' + #DynamicColumnsGQO + ', ' + #DynamicColumnsGQOTotal + ' as GQOToatl
FROM
(
SELECT
line.Account,
nom.AcctName,
line.ProfitCode + '' - '' + cc.PrcName as fieldname,
CASE WHEN line.Debit <> 0 THEN line.Debit *-1 WHEN line.Credit <> 0 THEN line.Credit ELSE 0 END as DispValue
FROM OJDT head
LEFT JOIN JDT1 line on head.TransId = line.TransId
LEFT JOIN OACT nom on line.Account = nom.AcctCode
LEFT JOIN OPRC cc ON line.ProfitCode = cc.PrcCode
WHERE head.RefDate BETWEEN ''' + CONVERT(VARCHAR(10),#DateFrom, 101) + ''' AND ''' + CONVERT(VARCHAR(10),#DateTo, 101) + '''
) AS SourceTable PIVOT
(
SUM(DispValue)
FOR fieldname IN (' + #DynamicColumnsDivision2 + ', '+#DynamicColumnsGQO2 + ')
) AS PivotTable;
'
--SELECT #Query
execute(#Query)
Edit 2
Weird I copied the entire proc and declared the date from and date to elements and it worked fine. So why when it being called from a stored proc is it working ok.
If the stored procedure does not return any data Crystal Reports won't be able to show you the columns. Make sure it returns the data.
Anyways, you can always try to remove the stored procedure and add it again in the database assistant. Crystal Reports is not very good updating the fields when you use a stored procedure, or at least it wasn't in older versions.

Change nulls to zeros (pivot table)

I have created stored procedure which creates pivoted table as below. The problem is that it doesn't work as expected because it doesn't change nulls to zeros. Could You please show me the right direction?
create procedure sp_system_counts
as
declare #columns nvarchar(max)
declare #columnscondition nvarchar(max)
declare #query nvarchar(max)
select distinct systemgroup, systemgroupsortorder into #temp_table_system_group
from systemgroups
where systemgroup not like 'N/A'
order by systemgroupsortorder
select #columns = isnull(#columns + ',', '') + '[' + convert(varchar, systemgroup) + ']' FROM #temp_table_system_group
select #columnscondition = + isnull(#columnscondition + ' or ', '') + '[' + convert(varchar, systemgroup) + '] <> 0' FROM #temp_table_system_group
--select #columns
create table #temp_systems (
systemid int,
systemnane varchar(max),
region varchar(50),
systemgroup varchar(50),
remsid int,
remscode int)
insert into #temp_systems
select distinct sy.systemid, sy.systemname, co.region, syg.systemgroup, re.remsid, re.remscode
from systems sy
inner join servers se on sy.systemid = se.systemid and sy.systemid = sy.systemid
inner join rems re on se.remsid = re.remsid
inner join cities ci on re.cityid = ci.cityid
inner join countries co on ci.countryid = co.countryid
inner join systemmodels sym on sy.systemmodelid = sym.systemmodelid
inner join systemtypes syt on sym.systemtypeid = syt.systemtypeid
inner join systemgroups syg on syt.systemgroupid = syg.systemgroupid
where syg.systemgroup not like 'N/A'
order by syg.systemgroup
set #query = '
select region, ' + #columns + '
from (
select distinct region, systemgroup, cnt = isnull(count(systemid),0) from #temp_systems
group by region, systemgroup
with rollup) p
pivot (sum (cnt) for systemgroup in (' + #columns + ')) as asd
where (' + #columnscondition +')'
execute(#query)
drop table #temp_table_system_group
drop table #temp_systems
I'm not sure, about logic implemented here, but may be it will help, if you change:
select #columns = isnull(#columns + ',', '') + '[' + convert(varchar, systemgroup) + ']' FROM #temp_table_system_group
select #columnscondition = + isnull(#columnscondition + ' or ', '') + '[' + convert(varchar, systemgroup) + '] <> 0' FROM #temp_table_system_group
to
select #columns = isnull(#columns + ',', '') + 'isnull(' + quotename(convert(varchar, systemgroup)) + ', 0) as ' + quotename(convert(varchar, systemgroup)) FROM #temp_table_system_group
select #columnscondition = + isnull(#columnscondition + ' or ', '') + 'isnull(' + quotename(convert(varchar, systemgroup)) + ', 0) <> 0' FROM #temp_table_system_group
i.e. doing isnull(.., 0) over pivoted data, not before pivoting

Step through 2 temp tables compare to table

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...)