calling functions in IN operators - sql-server

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?

Related

Why am i receiving Incorrect syntax near 'CAST' when assigning to an identifier

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
)
'
);

SQL Server 2012: Multiple select count(column1) in a single query from different table causing errors

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

SQL Server Insert Command Error

INSERT INTO BORCODEME
( BORCODEME.IslemTarihi, BORCODEME.IslemAciklamasi,BORCODEME.IslemTutari)
VALUES(
(SELECT BORCLAR.BorcTarih,BORCLAR.BorcAciklama,BORCLAR.BorcTutari FROM BORCLAR WHERE BORCLAR.BorcMusteriID=6),
(SELECT ODEMELER.OdemeTarihi,ODEMELER.OdemeAciklama,ODEMELER.OdemeTutar FROM ODEMELER WHERE ODEMELER.OdemeMusteriID=6)
)
My SQL command is this, and I have these errors;
Msg 116, Level 16, State 1, Line 4
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
Msg 116, Level 16, State 1, Line 6
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
Msg 109, Level 15, State 1, Line 1
There are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.
Not sure what you're really looking for - are you trying to insert the three columns from the two tables? Then write your INSERT like this:
INSERT INTO BORCODEME(IslemTarihi, IslemAciklamasi, IslemTutari)
SELECT
BORCLAR.BorcTarih, BORCLAR.BorcAciklama, BORCLAR.BorcTutari
FROM
BORCLAR
WHERE
BORCLAR.BorcMusteriID = 6
UNION
SELECT
ODEMELER.OdemeTarihi, ODEMELER.OdemeAciklama, ODEMELER.OdemeTutar
FROM
ODEMELER
WHERE
ODEMELER.OdemeMusteriID = 6
So this will insert the three values from BORCLAR and another row with the three values from ODEMELER.
If that's not what you want, then you need to explain in more detail what you really want instead.....
In general, you can either use this syntax:
INSERT INTO dbo.TargetTable (List-of-Columns)
VALUES (List-of-atomic-values)
or if you cannot provide atomic values (literals or T-SQL variables), then you can use
INSERT INTO dbo.TargetTable (List-of-Columns)
SELECT list-of-columns
FROM dbo.SourceTable
(but you cannot mix - you cannot have VALUES and then use SELECT inside of it)
In both cases, the number of columns in the INSERT statement must match exactly with the number of atomic values provided in VALUES or the number of columns selected by the SELECT statement

SQL Server append query

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

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