I'm trying to output the query results from one table and using that same variable as a 'like' in another table.
The first part of the query is supposed to get me everything *. The variable (or array) will be used in the second part of the query as part of 'like'.
This is what I have:
DECLARE #UpnPref nvarchar(100), #WC nvarchar(10)
Set #UpnPref = 0
Set #WC = '*'
Select #upnpref = UpnPrefix from dbo.ADUsers where UPNPrefix = #WC
print #upnpref <-- returns a 0
Select * from dbo.UserMailbox where LinkedAccount like '%' + #UpnPref +'%'
If what you're trying to do is select everything from dbo.UserMailbox that has LinkedAccount matching UpnPrefix of every record in dbo.ADUsers, you can do it so:
SELECT U.*
FROM dbo.UserMailbox U
INNER JOIN dbo.ADUsers A ON U.LinkedAccount = A.UpnPrefix
Related
We have a table LogicalTableSharing as follows:
For a specific requirement, we need to take PhysicalCompany of each TableCode into a variable.
We tried a case-based query as follows:
declare #tablecode varchar(50)
declare #inputcompany varchar(50)
declare #query nvarchar(2500)
set #inputcompany= 91
set #query = '
select '''+#inputcompany+''' AS inputcompany,
CASE WHEN lts.TableCode = ''tsctm005'' THEN lts.PhysicalCompany ELSE NULL END as tsctm005_company,
CASE WHEN lts.TableCode = ''tccom000'' THEN lts.PhysicalCompany ELSE NULL END as tccom000_company
from LogicalTableSharing lts
where lts.LogicalCompany = '''+#inputcompany+'''
'
EXEC sp_executesql #query
which obviously gives the result as
The desired output is
What is the right approach?
Try subqueries in a FROM-less SELECT. For performance you want an index on (logicalcompany, tablecode) (or the other way round depending on which is more selective).
SELECT #inputcompany inputcompany,
(SELECT TOP 1
physicalcompany
WHERE logicalcompany = #inputcompany
AND tablecode = 'tsctm005'
ORDER BY <some criteria>) tsctm005_company,
(SELECT TOP 1
physicalcompany
WHERE logicalcompany = #inputcompany
AND tablecode = 'tccom000'
ORDER BY <some criteria>) tccom000_company;
You should find <some criteria> to order by in case of multiple possible rows to decide which one takes precedence. Unless you just want a random one possibly each time you run the query another one, that is.
I have created a SQL Server function to return results based on two filter conditions. In TVF function I just have one select query where the results will be returned in table format. When I run the select query expected results were returned but when I run the same query through function then results are incorrect. Please advise as what is happening in SQL for TVF.
Function is not returning the expected results when we pass more values in parameters.
Sample table data:
answer_tag answer_text
-----------------------
TNBPDS1 250
TSMMBPDS 100
My code:
Create function [dbo].[OBSLookupByAnswerTextTagX]
(#pObsId int,
#pObsSeq tinyint,
#pAnswerTag varchar(10))
return #ReturnTable table
(
id int identity(1,1),
answer_text varchar(max),
answer_tag varchar(max)
)
begin
Insert into #ReturnTable (answer_text, answer_tag)
select distinct ansr.answer_text, ansr.answer_tag
from grp_bu_bs gbus
inner join benefit_summary bsum on (gbus.summary_id = bsum.summary_id)
inner join answer ansr on (gbus.summary_id = ansr.summary_id)
where
gbus.grp_prod_id = #pObsId
and gbus.grp_prod_seq = #pObsSeq
and #pAnswerTag like '%' + (ansr.answer_tag) + '%'
return
end
Below select query from function which gives expected result when we run the query as separate SELECT statement.
select distinct ANSR.answer_text,ANSR.answer_tag
from grp_bu_bs GBUS
inner join benefit_summary BSUM on (GBUS.summary_id = BSUM.summary_id)
inner join answer ANSR on (GBUS.summary_id = ANSR.summary_id)
where
GBUS.grp_prod_id = '189523'
and GBUS.grp_prod_seq = '31'
and 'TNBPDS1,TSMMBPDS,TNBPDS12,TNBPDSL3,TNBPDSD,TNBPDSAL' like '%' + ANSR.answer_tag) + '%'
If we have tag 'TNBPDS1' then 250 should be returned.
If we pass parameter as 'TNBPDS1,TSMMBPDS,TNBPDS12,TNBPDSL3,TNBPDSD,TNBPDSAL' results are returned as expected.
But if we pass parameter as 'TSMMBPDS,TNBPDS1,TNBPDS12,TNBPDSL3,TNBPDSD,TNBPDSAL' then no results are returned.
I already have some stored procedure, and now I want to make it one stored procedure.
My stored procedure code looks like this:
ALTER PROCEDURE [dbo].[UP_SELECT_TargetSiteStatus_For_ExcelExport]
#AppUrl nvarchar(200)
AS
BEGIN
SET NOCOUNT ON;
-- Web Application
SELECT
AppName, AppUrl, AppPort,
AppDefaultTimeZone, AppMaxiumFileSize,
AppContentDatabaseCount, AppSitesCount
FROM
tb_SPStatusWebApplications
WHERE
AppUrl = #AppUrl
-- Content Database
SELECT
ContentDBAppName, ContentDBID, ContentDBName,
ContentDBServerName, ContentDBStatus,
ContentDBSize, ContentDBSiteCount
FROM
tb_SPStatusContentDatabases CD
INNER JOIN
tb_SPStatusWebApplications WA ON CD.ContentDBAppName = WA.AppName
WHERE
CD.ContentDBAppName = ? <-- Change this...
END
In first Select query, AppName value is like this "Site1".
And I want to use AppName value to compare with ContentDBAppname in second SELECT query where clause
WHERE
CD.ContentDBAppName = [how to get AppNames value]
But I`m not sure how can I make it...
Please somebody help me
TRY THIS: your second select statement will be as below and you are already joining AppName in the join so you can add in AND condition as
AND WA.AppUrl = #AppUrl or in where.
SELECT
ContentDBAppName
, ContentDBID
, ContentDBName
, ContentDBServerName
, ContentDBStatus
, ContentDBSize
, ContentDBSiteCount
FROM tb_SPStatusContentDatabases CD
INNER JOIN tb_SPStatusWebApplications WA ON CD.ContentDBAppName = WA.AppName
AND WA.AppUrl = #AppUrl
It will return AppName exactly same as first select statement and will perform same in the join as per your expectation.
I am wanting to build a query that looks at an existing Models table.
Table Structure:
ModelID | ManufacturerID | CategoryID | ModelName
What I want to do is pass two things to the query, ModelID and ModelName, so that it returns the specific model and also similar models.
ModelName could be made up of several words e.g iPhone 5s 16GB, so what I would like my query to do is:
SELECT
M.*
FROM
Models AS M
WHERE
(M.ModelID = 1840 OR M.ModelName LIKE '%iPhone%'
OR M.ModelName LIKE '%5s%' OR M.ModelName LIKE '%16GB%')
Is there a way that I can pass the ModelName to the query as a string and then have the query split the string to generate the OR statements?
Do a web search for T-SQL split function. There are loads out there. They take a string (comma-delimited or space delimited or whatever) and return a table of values. Then just do a JOIN against that result set.
SELECT DISTINCT M.*
FROM Models AS M
JOIN dbo.fn_split(#model_name, ' ') AS model_names
ON M.ModelID = #model_id OR m.ModelName LIKE '%' + model_names.value + '%';
OK, so I managed to get this working, following the advice given by Kevin Suchlicki re. fn_Split.
I have made this function even more complex than i intended to, but in order to help others out in a similar situation, here is my final solution:
DECLARE #CategoryID int = 1
DECLARE #ManufacturerID int = 3
DECLARE #ModelName varchar(100) = 'iPhone 5s 16GB'
DECLARE #ModelID int = 1840
DECLARE #Carrier varchar(10) = NULL
DECLARE #Colour varchar(10) = NULL
SELECT
I.*
FROM
(
SELECT
DISTINCT M.*
FROM
Models AS M
JOIN
dbo.fn_Split(#ModelName,' ') AS N
ON M.ModelID = #ModelID OR lower(M.ModelName) LIKE '%'+ Lower(N.value) + '%'
WHERE
M.CategoryID = #CategoryID AND M.ManufacturerID = #ManufacturerID
) AS A
LEFT OUTER JOIN
Items AS I ON A.ModelID = I.ModelID
WHERE
I.Barred <> 1
AND I.Locked <> 1
AND I.Ber <> 1
AND I.Condition = 'Working'
AND (LOWER(I.Colour) = LOWER(ISNULL(#Colour, I.Colour)) OR I.Colour IS NULL)
AND (LOWER(I.Carrier) = LOWER(ISNULL(#Carrier, I.Carrier)) OR I.Carrier IS NULL)
I will now create this as a stored procedure to complete the job.
For reference, HERE is a link to the fn_Split function.
I have a stored procedure that I have scaled down considerably for the purpose of this question but in essence the issue I need assistance with is this.
If a row in table xyz is updated I need the ID's to be appended to each other and output back to the calling application. The update works as expected, the problem is in the manner in which I am building the output #IPV_ID_Found (see commented section at the bottom of the code).
#IPV_Status varchar (50),
#IPV_ID_Found varchar(500) = 'A' OUTPUT
IF (#IPV_Status ='closed')
BEGIN
UPDATE TEST_TBL
SET
Status = 'xyz',
WHERE
ID = #IPV_ID
-- this works for one ID
SELECT #IPV_ID_Found = (CAST(#IPV_ID AS VARCHAR(500)))
-- this does not work for multiple IDs
SELECT #IPV_ID_Found = #IPV_ID_Found + (CAST(#IPV_ID AS VARCHAR(500))) + ','
-- neither does this
SET #IPV_ID_Found = #IPV_ID_Found + (CAST(#IPV_ID AS VARCHAR(500))) + ','
SELECT #IPV_ID_Found
END
See the changes:
-- this does not work for multiple IDs
SELECT #IPV_ID_Found = #IPV_ID_Found + ',' + (CAST(#IPV_ID AS VARCHAR(500)))
then you will get a concatenated list of values, like 1,2,3,4,5
BUT if you need to return a recordset, then you need not OUTPUT parameter, use the table variable instead:
declare #IPV_ID_Found table(Item varchar(500))
IF (#IPV_Status ='closed')
BEGIN
UPDATE TEST_TBL
SET
Status = 'xyz',
WHERE
ID = #IPV_ID
-- this works for one ID
insert #IPV_ID_Found
VALUES (CAST(#IPV_ID AS VARCHAR(500)))
-- this does not work for multiple IDs
INSERT #IPV_ID_Found
VALUES (CAST(#IPV_ID AS VARCHAR(500)))
SELECT Item FROM #IPV_ID_Found
END