T-SQL selecting CTE into a variable - sql

I am attempting to set a variable to the result of a CTE select statement in SQL Server / T-SQL:
DECLARE #ReportRecipients VARCHAR(MAX);
SET #ReportRecipients = WITH CTE_TableName AS (SELECT a.emailTExt FROM
CSLEventAUP_Edit a JOIN CSLEventAUP_EventEditJunction b ON (a.Id = b.EditId)
JOIN CSLEventAUP_Events c ON (b.EventId = c.Id)
WHERE c.LogicalDeleteIn = 0
AND c.StaffEvent = 1
AND a.emailText IS NOT NULL
UNION
SELECT emailText FROM CSLEventAUP_Edit WHERE CyberGroup = 1)
SELECT TOP 1 STUFF((
SELECT ';' + emailTExt
FROM CTE_TableName t1
ORDER BY t1.emailText
FOR XML PATH('')),1, Len(';'), '') AS EmailTexts
FROM CTE_Tablename t0;
I get these errors:
Msg 156, Level 15, State 1, Procedure EmailSignAUPReminder, Line 38
[Batch Start Line 9]
Incorrect syntax near the keyword 'With'.
Msg 319, Level 15, State 1, Procedure EmailSignAUPReminder, Line 38 [Batch Start Line 9]
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
Running the query by itself results in
bob.xxx#mail.mil;bryan.xxx.xx#xx.mil;bryan.xx.xx#xx.edu;fred.coordinator#xx.mil

You need to define your CTE and SELECT its results in two separate steps. As this is structured, you are attempting to SELECT from an expression that does not yet exist.

Related

PIVOT in SQL Server does not support Select statement

I get these errors:
Msg 156, Level 15, State 1, Line 22
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 22
Incorrect syntax near ')'
when running this code:
Select *
from
(select
DWF_Week_No
,DWF_Fuel_Name
,DWF_T_Sale
from
QF_FDashboard_Week_Fuel
where
DWF_Month_Name = 'October'
and DWF_Location_Name = 'Fitzroy') t
pivot
(sum(DWF_T_Sale)
for DWF_Fuel_Name in (select distinct DWF_Fuel_Name from QF_FDashboard_Week_Fuel)
) as pivot_table;
It is not possible to put a SELECT inside the IN in the PIVOT. You can find a workaround here. In your case it would be something like this:
DECLARE #col nvarchar(max) = (stuff( ( select distinct ',[' + Ltrim(rtrim(DWF_Fuel_Name)) +']' from QF_FDashboard_Week_Fuel FOR XML PATH('')),1,1,''))
EXEC('Select *
from
(select
DWF_Week_No
,DWF_Fuel_Name
,DWF_T_Sale
from
QF_FDashboard_Week_Fuel
where
DWF_Month_Name = ''October''
and DWF_Location_Name = ''Fitzroy'') t
pivot
(sum(DWF_T_Sale)
for DWF_Fuel_Name in ('+#col+')
) as pivot_table;
')

Is it possible to add SQL alias from subquery?

I want to add aliases to sql query from select subquery.
something like
SELECT
ID AS(
SELECT
TOP1 NAME
FROM MYTABLE
)
,NAME
,SURNAME
FROM PEOPLE
Is it possible?
Error:
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '('. Msg 102,
Level 15, State 1, Line 1 Incorrect syntax near ','. Msg 156, Level
15, State 1, Line 8 Incorrect syntax near the keyword 'and'
Only possible with this:
DECLARE #n VARCHAR(MAX), #sql VARCHAR(MAX)
SELECT TOP 1 #n = NAME FROM MYTABLE
SET #sql = 'SELECT ID AS ' + #n + ', NAME, SURNAME FROM PEOPLE'
EXEC(#sql)

SQL Union select get max length from result

I have query against a SQL Server database:
Select [Surname]
from [dbo].[customer]
union
Select 'Surname';
As result I have:
and I want get from result max(len( {result} ));. If I use:
Select max(len([Surname]))
from [dbo].[customer];
This is working correctly (in result I have 11), but I need add to compare column name.
Query:
Select max(len(Select [Surname]
from [dbo].[customer]
union
Select 'Surname'))
Return error:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near ')'.
Try changing it to
Select max(len([Nazwisko]))
FROM (Select [Nazwisko] from [dbo].[wlasciciel] union Select 'Surname') t

stored procedure succeeds on one machine but fails on another?

Strange problem. When I create a stored procedure on one SQL server it succeeds but exactly the same code fails on another. They succeed both when the line 'select s from dbo.Split' is removed
The errors are
Msg 102, Level 15, State 1, Procedure DeliveryReportFFF, Line 38
Incorrect syntax near 'd2'.
Msg 102, Level 15, State 1, Procedure DeliveryReportFFF, Line 65
Incorrect syntax near '+'.
Msg 102, Level 15, State 1, Procedure DeliveryReportFFF, Line 75
Incorrect syntax near ')'.
Msg 156, Level 15, State 1, Procedure DeliveryReportFFF, Line 81
Incorrect syntax near the keyword 'AS'.
Msg 156, Level 15, State 1, Procedure DeliveryReportFFF, Line 87
Incorrect syntax near the keyword 'AS'.
Msg 156, Level 15, State 1, Procedure DeliveryReportFFF, Line 93
Incorrect syntax near the keyword 'AS'.
Msg 156, Level 15, State 1, Procedure DeliveryReportFFF, Line 101
Incorrect syntax near the keyword 'ORDER'.
The first error complains about the d2.DeliveryLocation as the argument to Split.
The SSMS version is 2012. What could be wrong here?
SELECT
row_number() over (order by o.OrderNumber, d2.DeliveryNumber, pd.TariffType) as Row
, d.BookTime
, d2.DeliveryRoute
, (select s from dbo.Split(' ', d2.DeliveryLocation) where pn = 2) as SorterExit
, d2.DeliveryLocation
FROM Delivery d WITH (NOLOCK)
The split UDF looks like this:
ALTER FUNCTION [dbo].[Split] (#sep nchar(1), #s nvarchar(512))
RETURNS table
AS
RETURN (
WITH tokens(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(#sep, #s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(#sep, #s, stop + 1)
FROM tokens
WHERE stop > 0
)
SELECT pn,
SUBSTRING(#s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
FROM tokens
)
Try using it as an outer apply.
SELECT row_number() over (order by o.OrderNumber, d2.DeliveryNumber, pd.TariffType) as Row
, d.BookTime
, d2.DeliveryRoute
, s.s as SorterExit
, d2.DeliveryLocation
FROM Delivery d WITH (NOLOCK)
OUTER APPLY dbo.Split(' ', d2.DeliveryLocation) as s

Msg 102, Level 15, State 1, Line 7 Incorrect syntax near ')'

Using this query:
select *
from
( Select DISTINCT status
From MNPdata
where IMSI_no = 'abc'
)
I got:
Msg 102, Level 15, State 1, Line 7 Incorrect syntax near ')'
Give the subquery an alias:
select *
from (
Select DISTINCT status From MNPdata where IMSI_no = 'abc'
) AS t
Since the subquery selects only status, you can do this instead:
Select DISTINCT status From MNPdata where IMSI_no = 'abc'