Has anyone managed to create a CTE in SQL Server's T-SQL that also includes a WITH XMLNAMESPACES declaration?
It seems both WITH keywords insist on being the "first in the T-SQL batch", and that doesn't really work....
I tried:
WITH XMLNAMESPACES('http://schemas.myself.com/SomeSchema' as ns)
WITH CTEQuery AS
(
SELECT (list of fields)
FROM dbo.MyTable
WHERE (conditions)
)
SELECT * FROM CTEQuery
Didn't work :-( (syntax errors)
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'WITH'.
Msg 319, Level 15, State 1, Line 2
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.
So I tried prepending the second WITH with a semicolon:
WITH XMLNAMESPACES('http://schemas.myself.com/SomeSchema' as ns)
;WITH CTEQuery AS
(
SELECT (list of fields)
FROM dbo.MyTable
WHERE (conditions)
)
SELECT * FROM CTEQuery
and got this:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near ';'.
and then I tried putting the WITH XMLNAMESPACES into the CTE:
WITH CTEQuery AS
(
WITH XMLNAMESPACES('http://schemas.myself.com/SomeSchema' as ns)
SELECT (list of fields)
FROM dbo.MyTable
WHERE (conditions)
)
SELECT * FROM CTEQuery
and got this:
Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword
'WITH'.
Msg 319, Level 15, State 1, Line 4
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.
Msg 102, Level 15, State 1, Line 21
Incorrect syntax near ')'.
So how the heck do I do this??
Use a comma instead of the second WITH, e.g.
WITH XMLNAMESPACES('http://schemas.myself.com/SomeSchema' as ns)
,CTEQuery AS
(
SELECT (list of fields)
FROM dbo.MyTable
WHERE (conditions)
)
SELECT * FROM CTEQuery
The same if you want multiple CTE expressions. You only need to specify WITH once, and then all other WITH blocks just use a comma instead of the keyword.
Related
I wrote a function (dbo.fFunctionCols) with 2 parameters (1st is tablename, 2nd is search pattern for column names) that returns certain column names from a table and passes them to the query below in which the same table is unpivoted. The query should end up as a view.
SELECT Id, AB, vTime, vItem, vCount
FROM
(SELECT Id, AB, vTime,
dbo.fFunctionCols('tablename', 'abc%def')
FROM dbo.[tablename]) AS piv
UNPIVOT
(vCount FOR vITEM IN
(SELECT dbo.fFunctionCols('tablename', 'abc%def') AS t1
) AS unpiv;
GO
SQL Server always returns:
Msg 156, Level 15, State 1, Line 8
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near ')'.
The statement:
SELECT dbo.fFunctionCols('tablename', 'abc%def') AS t1
works properly if executed. It delivers the correct list of the relevant column names seperated with commas and enclosed in square brackets.
What´s the error? Why can the function not be used inside the IN operator?
I am recieveing the following error
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'CAST'.
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'AS'.
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'AS'.
When I execute the code below:
SET #BrandMarket = CONCAT(
'(CAST((SELECT COUNT (*) FROM [2018].[dbo].[USA19SoybeanTraitRawData] WHERE [2018].[dbo].[USA19SoybeanTraitRawData].[',
#BrandCol,
'] = ',
#CodeID,
') AS FLOAT)*100) / CAST((SELECT COUNT (*) FROM [2018].[dbo].[USA19SoybeanTraitRawData] WHERE [2018].[dbo].[USA19SoybeanTraitRawData].[',
#BrandCol,
'] IS NOT NULL) AS FLOAT)'
);
I the expect to execute the Select statement by:
INSERT #BrandMarketCodePer EXECUTE (#BrandMarket);
You should always provide the DBMS name to got a proper and faster response as each DBMS has their own version of SQL except the basic SQL commands. Going by your code, I guessed that your DBMS was probably SQL Server.
A CAST statement on its own is not an executable command. You have a missing SELECT. --> this was your reason of the error.
You do not need to provide the table name in your where clause when you have only one table used in your query. If you are using more than one table, you should try using an alias name for each table to make the code better readable. <-- this was not source of the error, but a recommendation.
I also removed a few unnecessary parenthesis and indented the code properly for better readability.
You can try this way (if your DBMS is SQL Server):
SET #BrandMarket = CONCAT('SELECT
CAST(
(
SELECT COUNT (*)
FROM [2018].[dbo].[USA19SoybeanTraitRawData]
WHERE [', #BrandCol, '] = ', #CodeID, '
) AS FLOAT
)*100
/
CAST(
(
SELECT COUNT (*)
FROM [2018].[dbo].[USA19SoybeanTraitRawData]
WHERE [', #BrandCol, '] IS NOT NULL
) AS FLOAT
)
'
);
I am having trouble with my query, i am trying to do a pivot table using data from SQL and I want to sum up figures from a table for all years past from 2000.
This is my query
SELECT
*
FROM
(SELECT
Vendor_code, Vendor_name, Ord_date, SubTot,
DateRecieved, CurrencyCode, YearReceived
FROM
[BL_CUSTOM PO HISTORY SUMMARY]) AS S
PIVOT
(SUM(S.SubTot)
FOR s.YearRecived IN (SELECT STUFF((SELECT ', ' + cast(year as VARCHAR(10)) FROM [BL_CUSTOM YEAR COUNT] FOR XML PATH('')),1,1,'')) ) as pvt
I am getting the following error:
Msg 156, Level 15, State 1, Line 33
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 33
Incorrect syntax near ')'.
Refer to the syntax in https://learn.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017
I believe your query,
SELECT STUFF((SELECT ', ' + cast(year as VARCHAR(10)) FROM [BL_CUSTOM YEAR COUNT] FOR XML PATH('')),1,1,''))
is causing the problem.
I am trying to fetch counts from different tables in SQL Server 2012.
My query looks like:
SELECT
(
(SELECT COUNT(dbo.Table1.column1) FROM dbo.Table1) AS A,
(SELECT COUNT(dbo.Table2.column1) FROM ddbo.Table2) AS B,
(SELECT COUNT(dbo.Table3.column1) FROM dbo.Table3) AS C
)
I get these errors:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'AS'.
Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'AS'.
Msg 156, Level 15, State 1, Line 6
Incorrect syntax near the keyword 'AS'.
Msg 156, Level 15, State 1, Line 8
Incorrect syntax near the keyword 'AS'.
Msg 156, Level 15, State 1, Line 10
Incorrect syntax near the keyword 'AS'.
Please help me out of this situation.
Change to:
SELECT
(Select count(dbo.Table1.column1) from dbo.Table1) AS A,
(Select count(dbo.Table2.column1) from dbo.Table2) AS B,
(Select count(dbo.Table3.column1) from dbo.Table3) AS C
You can use a common table expression:
WITH A(c) as (SELECT count(1) c FROM table1),
B(c) AS (SELECT count(1) c FROM table1)
SELECT A.c, B.c FROM A, B
I have the following (not working) query:
insert into [MyDB].[dbo].[Reports_StepsStat]
(ActivityID,TaskID,StepIndex,StepStatus,TimeSpanInSeconds,Score)
VALUES (
SELECT
tasks.ActivityID as ActivityID,
tasks.ID as TaskID,
[StepIndex]=item.value('(StepIndex)[1]', 'NVARCHAR(MAX)'),
[StepStatus]=item.value('(Status)[1]', 'NVARCHAR(MAX)'),
[TimeSpanInSeconds] = DATEDIFF(MINUTE, item.value('(StartedOn)[1]', 'datetime'),item.value('(FinishedOn)[1]', 'datetime')),
tasks.Score as Score
FROM
[MyDB].[dbo].[Tasks] as tasks
CROSS APPLY
[Progress].nodes ('//Progress/Steps/ProgressStep') Progress(item)
)
The inner select query (SELECT task.ActivityID..) works perfectly and produces the expected table.
The outer insert into part is supposed to append the result of the inner part to a table by the name of Reports_StepsStat. This does not work.
I have tried and succeeded doing that with SELECT INTO, but apparently SELECT INTO can only be used to create a new table, and not to append to an existing table, which is what I need.
The errors I get are:
Msg 156, Level 15, State 1, Line 6
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near ')'.
I think VALUES ( is not required in your query.
insert into [MyDB].[dbo].[Reports_StepsStat]
(ActivityID,TaskID,StepIndex,StepStatus,TimeSpanInSeconds,Score)
SELECT
tasks.ActivityID as ActivityID,
tasks.ID as TaskID,
[StepIndex]=item.value('(StepIndex)[1]', 'NVARCHAR(MAX)'),
[StepStatus]=item.value('(Status)[1]', 'NVARCHAR(MAX)'),
[TimeSpanInSeconds]=DATEDIFF(MINUTE,item.value('(StartedOn)[1]', 'datetime'),
item.value('(FinishedOn)[1]', 'datetime')),
tasks.Score as Score
FROM [MyDB].[dbo].[Tasks] as tasks
CROSS APPLY [Progress].nodes ('//Progress/Steps/ProgressStep') Progress(item)
Syntax is
insert into a select * from b
so just omit the values (...) surroundng the select...