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)
Related
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.
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;
')
I am inserting a job step in Azure Elastic job agent. This is my code:
EXEC jobs.sp_add_jobstep #job_name='Sample T-SQL',
#command=N' declare #columns varchar(max)
select #columns = stuff(( select '],[' + [$Name]
from dbo.groups
order by '],[' + convert(varchar(max), [$_ClosingBalance]) desc
for xml path('')), 1, 2, '' + ']'
INSERT INTO dbo.Trial1
( [Bank Accounts],[Bank OD A/c],[Branch / Divisions],[Capital Account],[Cash-in-Hand],[Current Assets],[Current Liabilities],[Deposits (Asset)]
,[Direct Expenses],[Direct Incomes],[Duties & Taxes],[Fixed Assets],[Duties & Taxes1],[Duties & Taxes2],[Indirect Expenses],[Indirect Incomes],[Investments]
,[Loans & Advances (Asset)],[Loans (Liability)],[Misc# Expenses (ASSET)],[Provisions],[Purchase Accounts],[Reserves & Surplus],[Sales Accounts],[Secured Loans]
,[Stock-in-Hand],[Stock Transfer Outward],[Sundry Creditors],[Sundry Debtors],[Suspense A/c],[Duties & Taxes3]
,[Unsecured Loans]
)
Select * from (
Select [$_ClosingBalance], RowN = Row_Number() over (order by #columns) from dbo.Groups
) a
pivot (max([$_ClosingBalance]) for RowN in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31],[32])) p
INSERT INTO dbo.Date ([Date]) VALUES (GETDATE())
INSERT INTO dbo.Final
SELECT *
FROM dbo.Trial1
INNER JOIN dbo.Date
ON dbo.Trial1.IdCol = dbo.Date.IDCol1'',
#credential_name='JobRun',
#target_group_name='DatabaseGroup5'
I am receiving the following error :
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near ']'.
Msg 137, Level 15, State 2, Line 15
Must declare the scalar variable "#columns".
Msg 102, Level 15, State 1, Line 24
Incorrect syntax near ''
My code is ending where it should not. Please help.
after that you assigned #command ,you can write : print #command
then you can look printed script ,copy it and paste in query window.then probebly you will understand your mistake.
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
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