SQL Server append query - sql-server

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...

Related

calling functions in IN operators

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?

Is there a way in the STUFF(... FOR XML) function in SQL to prevent duplicate values?

To keep this short, here's my SQL code:
SELECT
EmailAddress,
FormsSubmitted = STUFF(
(
SELECT ',' + SourceSubType
FROM UK_AGT_AgentForms_TEST_DE a
WHERE a.EmailAddress = b.EmailAddress
FOR XML PATH('')
), 1, 1, ''),
DEDate
FROM UK_AGT_AgentForms_TEST_DE b
GROUP BY b.EmailAddress, b.DEDate
And, here's the result set it produces:
Is there a way to prevent duplicate values from showing up in the FormsSubmitted column from within the query above? Or do I need to do some "post processing" to remove the duplicates?
Add a DISTINCT to the inner SELECT query.

Invalid STRING_SPLIT args in SQL Server

I am trying to parse a cell that is data type nvarchar(max) like it is csv in SQL Server 2017. I was hoping to use the STRING_SPLIT return a row of data for each value in the array-like string. However, when I run the following code I get an error.
select this_column
into #t
from that_table
where coordinate_x = 1
and coordinate_y = 7
select * from STRING_SPLIT(#t.this_column, ',')
Msg 4104, Level 16, State 1, Line 16
The multi-part identifier "#t.this_column" could not be bound
Msg 8116, Level 16, State 1, Line 16
Argument data type void type is invalid for argument 1 of string_split function
How can I parse this data?
You can't pass a table to a inline table function, you need to include it in your FROM:
SELECT {YourColumns}
FROM #t T
CROSS APPLY STRING_SPLIT(T.this_column, ',') SS;
You'll want to use a cross apply with your temp table
Here's a working example so you can see how that works:
DECLARE #TestData TABLE
(
[TestData] NVARCHAR(MAX)
);
INSERT INTO #TestData (
[TestData]
)
VALUES ( N'1,2,3,4,5,6,7,8,9');
SELECT [b].[value] FROM #TestData [a]
CROSS APPLY[STRING_SPLIT([a].[TestData], ',') [b];
So for your situation, just a small tweak to what you already have, something like:
SELECT [b].[value] FROM #t a
CROSS APPLY STRING_SPLIT(a.this_column,',') b

Incorrect syntax near the keyword 'SELECT' using IN clause

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.

Combine CTE "WITH" and a "WITH XMLNAMESPACES...." in SQL Server

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.

Resources