SQL Server Selecting multiple LIKE values in Report Builder - sql-server

I have a report where I'm trying to allow the user to select multiple predetermined LIKE values from a drop down list for their results in report builder. Is there a way I can do this? I have tried to use LIKE IN() but those two keywords don't seem to work together. Here is the code that I have. The code I have only works if I select one option.
DECLARE #Warehouse nvarchar(10)
DECLARE #Location nvarchar(10)
SET #Warehouse = 'Warehouse1'
SET #Location = 'IB'
SELECT Part
, Tag
, CurrentLocation AS 'Location'
, TotalQty
, DateTimeCreated
, datediff(hour, DateTimeCreated, getdate()) AS 'Hours in Location'
, User AS 'Last User'
FROM table1
WHERE datediff(hour, DateTimeCreated, getdate())>=1
AND Warehouse IN(#Warehouse)
AND(CurrentLocation LIKE '%' + #Location + '%')
ORDER BY 'Hours in Location' DESC, CurrentLocation

This would be best handled with a stored procedure. Here is a high-level description of how it would work. Each of the techniques can be learned at a low-level with some astute googling:
For your report dataset, call the stored procedure, pass your multi-valued parameter to a varchar parameter in the stored proc. For the rest of this answer, we'll call that parameter #MVList
In the stored proc, #MVList will be received as a comma-delimited string of all the options the user chose in the parameter list.
Write your SELECT query from Table1, JOINing to a Table-Valued Function that splits the #MVList (google SQL Split Function to get pre-written code), and produces a table with one row for each value that the user chose.
For the JOIN condition, instead of equals, do a LIKE:
INNER JOIN MySplitFunction(#MVList, ',') AS SplitFunction
ON Table1.CurrentLocation LIKE '%'+SplitFunction.value+'%'
The result of the query will be the IN/LIKE result you are looking for.

Thank you for your responses. This is what I ended up doing that fixed my problem.
SELECT Part
, Tag
, CurrentLocation AS 'Location'
, TotalQty
, DateTimeCreated
, datediff(hour, DateTimeCreated, getdate()) AS 'Hours in Location'
, User AS 'Last User'
FROM table 1
WHERE datediff(hour, DateTimeCreated, getdate())>=1
AND Warehouse in (#Warehouse)
AND LEFT(CurrentLocation,2) IN(#Location)
ORDER BY 'Hours in Location' DESC, CurrentLocation

Related

Select field_name base on the table id from each of the list

I have a problem.
I want to show field_name at my query 'select .. from .. where' clause.
In my logging table, the table only keep the [date],[table_id],[field_id] .. fields, i need to show the 'field_name' as well in my select but there is no any other table that i can 'join' to get the [field_name] based on [field_id] in my 'select .. from'. As I search from google it seems I can get the field_name from SQL system called 'sys.columns' table. but that is too complicated for my SQL level because this sys.coloums is not straight forward. it mixed all the table before all each field number depend on the table id itself.
anyone who know how to write a good query to select out the field_name pls help :)
log_list table
[date],[table_id],[field_id],[company_name],...
my current query :
SELECT
date , table_id , name as table_name
FROM
log_list join table_name_list on log_list.table_id = table_name_list.table_id
and log_list.company_name like '%something%'
WHERE
date between #startdate and #enddate
thank you for your attention.
Your tag didn't say what version of SQL Server you are using, assuming you are using 2008+ there is a system function
COL_NAME ( table_id , column_id )
which if you supply table_id and column_id would get you the name, for detailed reference check it out here: COL_NAME (Transact-SQL)
If that is not a valid option for you, look closer to sys.columns, the object_id it returns is actually the table's object_id and should be your table_id, so if you do something like following it should work:
select C.name AS column_name
...
FROM ...
...
join sys.columns C on yourtable.table_id = C.object_id and yourtable.column_id = C.column_id

Manipulate a string to be used in IN operator (SQL, SSRS)

I have an SSRS report with dataset that has query looking like this (simplified as the query is a lot more complex that this):
select *
from myTable
where country in (#Country)
#Country is a parameter and can have multiple values
It works fine, but we were asked to roll up all the values from one country to another one (the country is not in the list of parameters to be selected).
So for example we need to roll up all the records that belong to Canada to US if US was selected as one of the Countries essentially just replacing 'Canada' with 'US' in the dataset returned which is easy to achieve using REPLACE or even CASE statement. However, it gets a bit tricky with WHERE clause in the query. Does anyone know how to replace a string with another string so it's understood by IN operator?
If I simply do something like this:
select *
from myTable
where country in (replace(#Country, 'US', 'US,Canada'))
the query doesn't return anything and I understand the reasons behind it.
If I test this hardcoding the values like this:
select *
from myTable
where country in ('US', 'Canada')
it returns the correct rows of data. I think I'm looking for a way to join multiple values so it's understood properly by IN operator.
TIA,
-TS.
You can use Dynamic SQL to achieve this. All you need to do is pass country name in declaration at first line.
Look at the code below:
DECLARE #SQL NVARCHAR(2000), #Country VARCHAR(30) = 'Canada'
SELECT #SQL = CONCAT('
select
*
from myTable
where country in (',
CASE WHEN #Country = 'US' THEN '''US'', ''Canada''' else '#Country' end , ')'
)
EXEC sp_executesql #SQL, N'#Country VARCHAR(30)', #Country = #Country
Here's a fiddle : http://sqlfiddle.com/#!18/b7f49/4
Possibly the same answer as SQL in (#Variable) query
You may need to add REPLACE to that function based on your requirements.

Using data from SQL Server to generate report in Access?

I have a legacy VB6 application that's connected to SQL Server where all data is stored. I'm creating a report for the user where I'll need to pass 2 dates (FROM and TO). In SQL Server, I have created a few views that fulfill all my criteria and use the data from there to populate a dbo.tblTempTable (which is not actually #tempTable, but a normal table). For now the dates are hardcoded, and I'm struggling with finding a way of passing those dates. I'm pretty sure I am unable to pass parameters to a view. To populate the table I have a simple stored procedure that goes like this....
TRUNCATE TABLE dbo.tbl_TTableReport
INSERT INTO tbl_TTableReport (UserID, CompanyID, CompanyName, Sold, Voided, Returned, Subtotal)
SELECT
1234 AS USERID, CompanyID, CompanyName,
Sold, Voided, Returned, Subtotal
FROM dbo.vCompanyInfo
So in this select statement, every piece of data comes from my final view ..vCompanyInfo. Sold, Voided, and Returned need to be filtered by the FROM and TO dates. How would I do something like that?
EDITED. I'm trying to create a stored procedure but I'm getting some weird errors...I have never create a complex multi SELECT statement SP before so I'm still trying to work out the kinks.
This is me trynig to build a SP with select statement, but I keep seeing the same error : Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
TRUNCATE TABLE dbo.tbl_TTableReport
INSERT INTO tbl_TTableReport
(UserID
, CompanyID)
, CompanyName)
SELECT 1234 AS USERID
,(Select CompanyID from dbo.tblMainInv)
,(select CompanyName from dbo.tblCompanies)
For both the CompanyID and companyName there are about 30 values. I'm trying to have them get loaded into the table, I don't know where my error is.
I recommend you create an ADP Access project to connect to your SQL Server database. This allows you more control over the queries that you send to the Sql Server for reports and data entry forms. When creating the project file you designate the server and database with which you need to connect to. Then setting up the data source for your report is as simple as including the select statement to issue against the database into the data source of the report. You can also refer to text boxes on forms or have automatic prompts for parameters.
As for the error you are getting in your second query in your edit... you are using the sub-query as an expression. SQL Server is being nice in letting you use a sub-query as one of the values to output in your select statement, but it's expecting just that... one value. So you could do something like:
Select
(select count(*) from MyTableValues) as CountTotal,
(select sum(*) from MyTableValues) as SumTotal
However, what you are trying to do is return several rows when SQL Server is expecting you to return just one. If you want to join the data of two tables, you use a join... something like:
SELECT 1234 AS USERID, CompanyID, CompanyName
from dbo.tblMainInv
join dbo.tblCompanies
on tblMainInv.CompanyID = tblCompanies.CompanyID
Which is probably something that your view dbo.vCompanyInfo probably already looks like.
If your determined to use your temp table approach (although I highly recommend you reconsider as your just making more work for future maintenance)... this is something that your procedure might look like:
GO
CREATE PROCEDURE sp_LoadReportData
(
#UserID as int,
#StartDate as datetime,
#EndDate as datetime
) AS
delete from tbl_TTableReport
where USERID = #UserID
INSERT INTO tbl_TTableReport
(UserID, CompanyID, CompanyName, Sold, Voided, Returned, Subtotal)
SELECT
#UserID AS USERID,
CompanyID,
CompanyName,
Sold,
Voided,
Returned,
Subtotal
FROM vCompanyInfo
where
Sold between #StartDate and #EndDate
and Voided between #StartDate and #EndDate
and Returned between #StartDate and #EndDate
GO
You would then call the procedure with the filters you want and send the UserID as a parameter like this:
exec sp_LoadReportData 1234, '1/1/2016', '1/20/2016'
But this still doesn't solve your problem... because you'll still have to send the UserID as a parameter in your report's data source like:
select * from tbl_TTableReport where UserID=1234
Unless you want to create a table and procedure for every user, you should really rethink your strategy and learn how to do it the standard way.

TSQL Conditional Where Based on Another Table

I have a stored procedure that contains a simple query like below. The query pulls down all the bids that have been submitted on a job.
I need to add in an additional piece to the WHERE clause however.
There is a second table called Admins and a field within the table called employeeID. If the employees ID that's being passed to the stored procedure exists in Admins it will pull down all bids. If they do not exist in Admins it will only pull down bids where b.actor = #employee.
In short, if #employee exists in Admin, leave the where clause how it is (pulling down all information for the requestID. However if they are not in that table, need to add in AND b.actor = #employee
SELECT b.bidID ,
b.requestID ,
b.notes ,
b.team ,
b.devDays ,
b.complexity ,
b.estimatedCost ,
b.actor ,
b.status,
REPLACE(CONVERT (VARCHAR (20), b.timestamp, 106), ' ', '-') AS timestamp,
e.PreferredName AS bidderFirstName,
e.LastName AS bidderLastName,
e.NTID AS bidderNTID
FROM dbo.BS_ToolRequests_Bids AS b
LEFT OUTER JOIN dbo.EmployeeTable AS e
ON b.actor = e.QID
WHERE b.requestID = t.requestID
FOR XML PATH ('data'), TYPE, ELEMENTS, ROOT ('bids')
How can I go about doing this? The code above is a sub select in a larger query but need to add some type of condition to it.
Can you add an OR clause to your existing WHERE clause?
WHERE
AND ( EXISTS(SELECT 'f' FROM Admins WHERE employeeid = #employeeid)
OR b.actor = #employeeid
)

Multiple selects in stored procedure using union - Noob

I have searched for answers but find myself more confused. I am not as experienced - but with low staff - and just me creating reports - I have to create this.
Client has asked for a report that will return MTD answers on survey questions that are stored in 2 databases. Problem is - they want records that are attached to each submitted answer that are not a part of the survey. i.e. each respondent has a information regarding what type of phone they have, area they live in, model of phone and days of service. (these are not answers though)
Many of them are unique. (Models and Cities)
So for example I have created a stored procedure in SQL to pull into SSRS to display results.
But each one is a select and I am only getting the first result. I tried adding UNION ALL but it doesn't seem to let me group them when I do this. I get everything in one column, where as I need them in separate columns - horizontally ideally. But that may be asking too much.
Here is an example - perhaps there is a quicker way - this is a monstrous project - and my deadline is running short now - and I have tried so many things - and searching. Nothing left to do but ask for help.
So here is what I have -
ALTER PROCEDURE [dbo].[TEST_WIRELESS_DISCO_SURVEY_RESULTS]
(
#STARTDATE DATETIME,
#ENDDATE DATETIME
)
AS
BEGIN
SELECT
a.CUSTOM17 as 'Make', COUNT(ISNULL(A.custom17, 0)) as 'Total Make'
FROM GCI_SURVEYS as a
JOIN GCI_Post_Survey_PreRepair_Master as b ON a.CustAcctNo = b.CustAcctNo
WHERE b.Trans_Date between #STARTDATE and #ENDDATE
AND a.i3_rowid = 'GCI_WRLSDISC_BSV'
AND a.Q01 = 'no'
GROUP BY CUSTOM17
UNION ALL
SELECT
a.CUSTOM22 as 'Market', COUNT(ISNULL(a.CUSTOM22, 0)) as 'Total Market'
FROM GCI_SURVEYS as a
JOIN GCI_Post_Survey_PreRepair_Master as b ON a.CustAcctNo = b.CustAcctNo
WHERE b.Trans_Date between #STARTDATE and #ENDDATE
AND a.i3_rowid = 'GCI_WRLSDISC_BSV'
AND a.Q01 = 'no'
GROUP BY a.CUSTOM22
From your explanation, I would think that the top part of the union and the bottom contain the same surveys, just different parts?
I personally would load them into variable tables (or if alot of records, tempoary tables), and then join them together.
DECLARE #MakeQuestion TABLE
(
survery_id INT --datatype
,make VARCHAR(200) --replace with your own
,total_make INT
)
INSERT INTO #MakeQuestion
SELECT a.join_condition, a.CUSTOM17 as 'Make',COUNT(ISNULL(A.custom17,0)) as 'Total Make'
FROM GCI_SURVEYS as a
JOIN GCI_Post_Survey_PreRepair_Master as b
ON a.CustAcctNo = b.CustAcctNo
WHERE b.Trans_Date between #STARTDATE and #ENDDATE
AND a.i3_rowid = 'GCI_WRLSDISC_BSV'
AND a.Q01 = 'no'
GROUP BY a.join_condition,CUSTOM17
DECLARE #MarketQuestion TABLE
(
survery_id INT -- datatype
,market VARCHAR(200) --replace with your own
,total_market INT
)
Insert INTO #MarketQuestion
SELECT a.join_condition, a.CUSTOM22 as 'Market',COUNT(ISNULL(a.CUSTOM22,0)) as 'Total Market'
FROM GCI_SURVEYS as a
JOIN GCI_Post_Survey_PreRepair_Master as b
ON a.CustAcctNo = b.CustAcctNo
WHERE b.Trans_Date between #STARTDATE and #ENDDATE
AND a.i3_rowid = 'GCI_WRLSDISC_BSV'
AND a.Q01 = 'no'
GROUP BY a.CUSTOM22
SELECT *
FROM #MakeQuestion Make
INNER JOIN #MarketQuestion Market ON Make.survey_id = Market.survery_id
Please let me know if i misunderstood.
In the Question you stated that you are fetching data from two Database
return MTD answers on survey questions that are stored in 2 databases
In you SP you are Selecting from the same the DB
Just add the Database Name in one of your Select Query

Resources