What is the use of with clause in SQL Server [duplicate] - sql-server

This question already has answers here:
When to use with clause in sql
(2 answers)
Closed 9 years ago.
Please anybody can help me to understand the use of WITH clause
WITH T(Id) AS
(SELECT DISTINCT
[IO].[IncidentQuestionId]
FROM
[dbo].[IncidentValue] AS IV
INNER JOIN
[dbo].[IncidentOption] AS [IO] ON [IV].[IncidentOptionId] = [IO].[Id]
WHERE
[IV].[IncidentId] = 45
)
SELECT
IQ.*, IC.[Name] AS [IncidentCategory]
FROM
IncidentQuestion] AS IQ
INNER JOIN
T ON [T].[Id] = IQ.[Id]
INNER JOIN
[dbo].[IncidentCategory] AS IC ON IQ.[IncidentCategoryId] = IC.[Id]
WHERE
IQ. [IsOption] = 0
ORDER BY
IC.[OrderId] ASC, IQ.[OrderId] ASC
I have the query above which uses the with clause but im not aware of the use of with clause.
thanx

It's a syntax for Common Table Expressions. Read documentation Using Common Table Expressions

It is used to create a Common Table Expression, which returns a result of a SELECT statement which then can be used in yet another SQL statement.
I use them to produce better readable SQL code.

For sometimes,WITH clause is used to force a query to use an Index.

Related

How to concatenate group members into a resulting column of an SQL query [duplicate]

This question already has answers here:
Optimal way to concatenate/aggregate strings
(8 answers)
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
(12 answers)
Closed 11 months ago.
I have 2 related tables as given below where I need to concatenate the names of group members into a query result as given below:
I am not sure whether this is possible with SQL. I tried to use group by, but I do not know a useful expression to search for concatenation in the context of group by. Any hints where and with what key words to search for will be gratefully appreciated.
use String_agg as follows
SELECT groupid,
groupname,
String_agg(groupmembername, ',') AS GroupMemberName
FROM lefttable1 t1
JOIN righttable2 t2
ON t1.groupid = t2.groupid
GROUP BY groupid,
groupname
or as follows
SELECT groupid,
groupname,
String_agg(groupmembername, ',') AS GroupMemberName
FROM (SELECT groupid,
groupname,
groupmembername
FROM lefttable1 t1
JOIN righttable2 t2
ON t1.groupid = t2.groupid) T3

SQL Join: Everything in the LEFT table that is NOT IN the RIGHT Table [duplicate]

This question already has answers here:
What's the best way to use LEFT OUTER JOIN to check for non-existence of related rows
(4 answers)
Closed 4 years ago.
I have two tables, "Affiliates" and "ControlPanels".
ControlPanels has a field (CP_AffiliateID) that maps to Affiliates (A_ID).
I want to select all records from Affiliates that DO NOT have a match in CP_AffiliateID.
The fields A_ID is a Primary Key so I'm not worried about matching NULL.
What would that join look like?
Please try NOT IN
SELECT *
FROM affiliates
WHERE affiliates.a_id NOT IN (SELECT cp_affiliateid
FROM controlpanels)
You don't really need a join for this and can just use != ALL (subquery).
SELECT * FROM Affiliates A
WHERE a.A_ID != ALL (SELECT C.CP_AffiliateID FROM ControlPanels C)

Need to update one column for records where another value is duplicative in SQL Server [duplicate]

This question already has answers here:
Update a table using JOIN in SQL Server?
(13 answers)
Closed 7 years ago.
I am VERY rusty with my SQL, it's been a few years, but I need to write a query to fix something in a table I have.
There are erroneous duplicates where not every column is the same, but I know at least one is.
So I have this query that works:
SELECT
[IntMsgID], [SortDate], COUNT(*)
FROM
[databasename].[dbo].[tblDoc]
GROUP BY
[IntMsgID], [SortDate]
HAVING
COUNT(*) >= 2
AND [IntMsgID] IS NOT NULL
It identifies the documents in question. What I need to do, then, is take the results from that and update another field simply with the value of Y or 1.
I've done searching and it seems any query I've tried to plug in fails, such as
UPDATE [databasename].[dbo].[tblDoc] AS t
INNER JOIN
(SELECT [IntMsgID] msgid
FROM [databasename].[dbo].[tblDoc]
GROUP BY [IntMsgID]) t1 ON t.[IntMsgID] = t1.[IntMsgID]
SET [JG_SQLDupe] = 'Y'
I get syntax errors at "AS" and "INNER" and "t1"
I would use a CTE to achieve this:
;with updts as (SELECT [IntMsgID], [SortDate], count(*)
FROM [databasename].[dbo].[tblDoc]
Group By [IntMsgID], [SortDate]
HAVING count(*) >= 2 AND [IntMsgID] is not null)
update t
set t.Flag = 'Y'
from [databasename].[dbo].[tblDoc] t inner join
updts u on t.[IntMsgID] = u.[IntMsgID]
and t.[SortDate] = u.[SortDate]

Is there any perform difference on the sequencce of clause "ON" in "JOINs"? [duplicate]

This question already has an answer here:
In mysql which inner join sql is most effective and best?
(1 answer)
Closed 7 years ago.
Is there any perform difference on the sequence of clause "ON" in "JOINs"?
SELECT * FROM a JOIN b ON a.id = b.id
SELECT * FROM a JOIN b ON b.id = a.id
In this simple case not. But to be 100% sure compare execution plan and statistic.
SET SHOWPLAN_TEXT ON
SET SHOWPLAN_ALL ON
SET SHOWPLAN_XML ON
SET STATISTICS PROFILE ON
SET STATISTICS XML ON
<your queries>
No it does not make a difference. You can check this article: Does order matter in a JOIN clause? which provides the details about the same.
Query #2 produced the exact same execution plan! So, we can conclude
from this simple example that the order of tables referenced in the ON
clause of a JOIN doesn't affect the performance of a query.

Use columns from select statement as parameter in function when joining [duplicate]

This question already has an answer here:
pass parameter in table valued function using select statement
(1 answer)
Closed 7 years ago.
Consider the following sql query:
SELECT TaskId,FromItemId, IHV_FROM.NodePath as FromPath
FROM VIEW_TASKS with (nolock)
left Join fn_ITEM_HIERARCHY(FromItemId) IHV_FROM ON FromItemId = IHV_FROM.ItemId
WHERE ...
fn_ITEM_HIERARCHY is a function which takes one input parameter. I would like to use FromItemId from VIEW_TASKS as input parameter to the function.
When doing it like above, i get the error (Microsoft SQL Server 2008) "Invalid column name".
The SELECT statement returns multiple values, so it is not possible to assign the value to a variable in a separate select statement. Any ideas?
You probably need to use OUTER APPLY in this case:
SELECT TaskId,FromItemId, IHV_FROM.NodePath as FromPath
FROM VIEW_TASKS with (nolock)
OUTER APPLY fn_ITEM_HIERARCHY(FromItemId) IHV_FROM
WHERE ...
;
If the function always returns rows or if you only want results for values where the function does return rows, use CROSS APPLY instead.
Use Cross apply as shown here
http://blog.sqlauthority.com/2008/01/03/sql-server-2005-last-ran-query-recently-ran-query/
use alias
SELECT t.TaskId, t.FromItemId, IHV_FROM.NodePath as FromPath
FROM VIEW_TASKS t with (nolock)
left Join fn_ITEM_HIERARCHY(FromItemId) IHV_FROM ON t.FromItemId = IHV_FROM.ItemId
use OUTER APPLY instead of left join

Resources