Solved

Error converting query to inline function

Posted on 2009-07-03
18
213 Views
Last Modified: 2012-05-07
I have a query that I need to convert to a function.  The query will return the desired table.
When I try to save the function I get the errors:
Incorrect syntax near the keyword 'Declare'.
Incorrect syntax near 'Returns'.
Must declare the scalar variable "@Cols".
Must declare the scalar variable "@Cols".
Incorrect syntax near 'end'

Any help will be appreciated
CREATE FUNCTION dbo.TaskStatusPivot
 

Declare @strSQL varchar(max)

DECLARE @cols varchar(2000)
 

RETURNS TABLE

AS

	RETURN 

	SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT

                                '],[' + task

                        FROM    WeekTaskStatus

                        ORDER BY '],[' + task

                        FOR XML PATH('')

                      ), 1, 2, '') + ']'

 

 

set @strSQL = 'select WeekEnd, ' + @cols +

		' from (

			select WeekEnd, Task, TaskStatus from WeekTaskStatus) o

		  pivot (Max(TaskStatus) for Task in (' + @cols + ')) p'

 

exec(@strSQL) 
 

end

Open in new window

0
Comment
Question by:Scamquist
  • 6
  • 5
  • 4
  • +2
18 Comments
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 24772210
functions cannot have dynamic sql.
you will need to stick with a stored procedure or some other method.
0
 
LVL 17

Expert Comment

by:pssandhu
ID: 24772218
You do not use Decalre keyword when settnig parameters. Try this:
CREATE FUNCTION dbo.TaskStatusPivot (@strSQL varchar(max),@cols varchar(2000))
 

RETURNS TABLE

AS

BEGIN	

	SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT

                                '],[' + task

                        FROM    WeekTaskStatus

                        ORDER BY '],[' + task

                        FOR XML PATH('')

                      ), 1, 2, '') + ']'

 

 

set @strSQL = 'select WeekEnd, ' + @cols +

		' from (

			select WeekEnd, Task, TaskStatus from WeekTaskStatus) o

		  pivot (Max(TaskStatus) for Task in (' + @cols + ')) p'

 

RETURN exec(@strSQL) 

 

end

Open in new window

0
 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 24772222
You cannot run dynamic sql within a function, you should change this to a stored proc
0
 
LVL 17

Expert Comment

by:pssandhu
ID: 24772241
Errr.. correct need to change the dynamic sql too
0
 
LVL 1

Author Comment

by:Scamquist
ID: 24772279
I tried the code below.
I now get the error:

Incorrect syntax near the word 'Declare'.
CREATE PROCEDURE dbo.TaskStatusPivot
 

Declare @strSQL varchar(max)

DECLARE @cols varchar(2000)
 
 

	RETURN

	SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT

                                '],[' + task

                        FROM    WeekTaskStatus

                        ORDER BY '],[' + task

                        FOR XML PATH('')

                      ), 1, 2, '') + ']'

 

 

set @strSQL = 'select WeekEnd, ' + @cols +

		' from (

			select WeekEnd, Task, TaskStatus from WeekTaskStatus) o

		  pivot (Max(TaskStatus) for Task in (' + @cols + ')) p'

 

exec(@strSQL)

Open in new window

0
 
LVL 31

Expert Comment

by:RiteshShah
ID: 24772289
>>You do not use Decalre keyword when settnig parameters. Try this:<<

will this change work? ;)
0
 
LVL 31

Expert Comment

by:RiteshShah
ID: 24772305
I also suggest to use Stored procedure as dynamic SQL is not permitted in function.
0
 
LVL 1

Author Comment

by:Scamquist
ID: 24772317
RiteshShah
Try what?

Replace
Declare @strSQL varchar(max)
DECLARE @cols varchar(2000)
with
(@strSQL varchar(max),@cols varchar(2000))

I am not sure what you mean by:
>>You do not use Decalre keyword when settnig parameters. Try this:<<
0
 
LVL 31

Expert Comment

by:RiteshShah
ID: 24772398
I was asking to pssandhu as he said to change something and which suppose to work in function.

For you, all I can say is, your function will not work at all if it has dynamic SQL
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 1

Author Comment

by:Scamquist
ID: 24772445
I did deleted the function attempt and tried to create a Stored Procedure.

When I tried the Stored Procedure in the attached code, I got the error:

Incorrect syntax near the word 'Declare'.
CREATE PROCEDURE dbo.TaskStatusPivot

 

Declare @strSQL varchar(max)

DECLARE @cols varchar(2000)

 

 

	RETURN

	SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT

                                '],[' + task

                        FROM    WeekTaskStatus

                        ORDER BY '],[' + task

                        FOR XML PATH('')

                      ), 1, 2, '') + ']'

 

 

set @strSQL = 'select WeekEnd, ' + @cols +

		' from (

			select WeekEnd, Task, TaskStatus from WeekTaskStatus) o

		  pivot (Max(TaskStatus) for Task in (' + @cols + ')) p'

 

exec(@strSQL)

 

Open in new window

0
 
LVL 31

Accepted Solution

by:
RiteshShah earned 250 total points
ID: 24772456
try this:



CREATE PROCEDURE dbo.TaskStatusPivot

as

declare @strSQL varchar(max)

declare @cols varchar(2000)

 

        SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT

                                '],[' + task

                        FROM    WeekTaskStatus

                        ORDER BY '],[' + task

                        FOR XML PATH('')

                      ), 1, 2, '') + ']'

 

 

set @strSQL = 'select WeekEnd, ' + @cols +

                ' from (

                        select WeekEnd, Task, TaskStatus from WeekTaskStatus) o

                  pivot (Max(TaskStatus) for Task in (' + @cols + ')) p'

 

exec(@strSQL)

Open in new window

0
 
LVL 75

Assisted Solution

by:Aneesh Retnakaran
Aneesh Retnakaran earned 250 total points
ID: 24772462
CREATE PROCEDURE dbo.TaskStatusPivot
as
 
Declare @strSQL varchar(max)
DECLARE @cols varchar(2000)
SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                            '],[' + task
                    FROM    WeekTaskStatus
                    ORDER BY '],[' + task
                    FOR XML PATH('')
                  ), 1, 2, '') + ']'

 
set @strSQL = 'select WeekEnd, ' + @cols +
            ' from (
                  select WeekEnd, Task, TaskStatus from WeekTaskStatus) o
              pivot (Max(TaskStatus) for Task in (' + @cols + ')) p'
 
exec(@strSQL)
 
0
 
LVL 17

Expert Comment

by:pssandhu
ID: 24772556
Ritesh, I did not know you were aking me? lol. No, I corrected my self in the following post saying that he need to change the dynamic SQL after I saw angel's post since I didn't realise he was using dynamic SQL. His first error was "Incorrect syntax near DECLARE" so when I looked at his code, the decalre statements were between the CREATE FUNCTION statement and "RETURNS TABLE" statement I thought he is trying to set up parameters since you do not declare variables there.
Anyway, should have read through till the end. At work so trying take as much less time as possible answering.
P.
0
 
LVL 31

Expert Comment

by:RiteshShah
ID: 24772582
no problem, it happens sometime, I don't have .00001% doubts about your skill :) me either have to read full post ;)
0
 
LVL 1

Author Comment

by:Scamquist
ID: 24772670
The code saved.  
I have been trying to get this pivot statement to create a table when called.  

I am not sure of the protocol.  Do I need to create a new ee question ...or someone help with this?
0
 
LVL 17

Expert Comment

by:pssandhu
ID: 24772710
Hey Ritesh, it's all good man, I didn't mind considering I am the new kid on the block and still learning the art of answering effectively. ;-)
Scamquist, I think you should split points between Aneesh and Ritesh and open a new question.
P.
0
 
LVL 1

Author Comment

by:Scamquist
ID: 24772735
pssandhu:  -  WILL DO.  Thanks all
0
 
LVL 1

Author Closing Comment

by:Scamquist
ID: 31599556
I need to study what you did.  I have been trying for a few days to get a dynamic pivot query to work.  When I got the query to work, it wouldn't save.  The stored procedure was the next hurdle. I appreciate the help.
I will be posting a follow up question to get the stored prodcedure to create a table when called.  Thank you both for the assist
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
SQL joining table to itself to combine rows 5 30
SQL Login 17 38
SQL Server - Slabs 9 35
SQL 2008 R2 calc date formula 3 18
Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

930 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now