I’m attempting to create a variable that will hold a value, which I will then later use to select from a table using the variable value. This works perfectly the first time around, but any time I try and change the parameters to update the variable it returns blank. Am I able to use the same variable with different parameters? Or am I doing something wrong with my code?
Like I said, this method words great for 1 time and then afterward if I Print
the variable then it returns blank.
Here is an example of my variable working as expected.
DECLARE @ReportTitle as VARCHAR(100) SELECT @ReportTitle = ti.Title FROM dbo.tblSales ti WHERE ti.Title = (SELECT REPLACE(T1.Title, 'Sale', '') FROM dbo.tblSales t1 WHERE t1.IdCountry = 34 AND t1.IdReport = 3375 AND t1.IdLanguage= 1 and t1.btInUse = 1 ) PRINT @ReportTitle SELECT i.IdCountry as Country, i.Title as ReportTitle, i.Report as IndustryID FROM dbo.tblSales i WHERE i.IdCountry = 49 AND i.IdLanguag = 1 and i.btInUse = 1 AND i.Title LIKE '%' + @ReportTitle +'%'
Now If I run the same exact query but change AND t1.IdReport = 3375
to AND t1.IdReport = 3595
the print @ReportTitle
returns empty and the query I have written does not return any rows.
Here is an example of one that is not working:
DECLARE @ReportTitle as VARCHAR(100) SELECT @ReportTitle = ti.Title FROM dbo.tblSales ti WHERE ti.Title = (SELECT REPLACE(T1.Title, 'Sale', '') FROM dbo.tblSales t1 WHERE t1.IdCountry = 34 AND t1.IdReport = 3375 AND t1.IdLanguage= 1 and t1.btInUse = 1 ) PRINT @ReportTitle SELECT i.IdCountry as Country, i.Title as ReportTitle, i.Report as IndustryID FROM dbo.tblSales i WHERE i.IdCountry = 49 AND i.IdLanguag = 1 and i.btInUse = 1 AND i.Title LIKE '%' + @ReportTitle +'%'
My expected outcome is to use the variable to hold titles based on the IdReport
I pass.
For example, the first time around the variable prints Retail
which is what I am expecting, I then search for titles that includes %Retail%
Second time around I run the query using IdReport
= 3595 which returns the title Appointments
. Which if I print @ReportTitle it equals nothing when I expect it to equal Appointments
Advertisement
Answer
Was able to figure it out. It wasn’t a data issue so it was a bit tricky. Turns I may have had an extra SELECT that wasn’t needed.
Here is a code sample of working code for me:
DECLARE @ReportTitle as VARCHAR(100) (SELECT @ReportTitle = REPLACE(T1.Title, 'Sale', '') FROM dbo.tblSales ti WHERE t1.IdCountry = 34 AND t1.IdReport = 214 AND t1.IdLanguage= 1 and t1.btInUse = 1 ) SELECT i.IdCountry as Country, i.Title as ReportTitle, i.Report as IndustryID FROM dbo.tblSales i WHERE i.IdCountry = 21 AND i.IdLanguag = 1 and i.btInUse = 1 AND i.Title LIKE '%' + @ReportTitle +'%'