?
Solved

Common Table Expression and Execute

Posted on 2014-07-17
3
Medium Priority
?
204 Views
Last Modified: 2014-09-22
I have developed below

DECLARE @dbname VARCHAR(40)
SET @dbname = ( SELECT TOP 1
                        m.archetypecode + CONVERT(NVARCHAR, runindex)
                FROM   dbo.nxMetricRun mr
                        INNER JOINdbo.nxMetric m ON mr.MetricID = m.nxMetricID
                                                 AND mr.MetricTableName IS NULL
                WHERE   mr.Description = 'Matter Summary - Scheduled'
                ORDER BY mr.timestamp DESC
              )
   

EXECUTE ('select  mt.mattindex, sum(billfees) BillFees, m.wipbal,c.clibal, mt.number,mt.Displayname FeeEarner,MattStatus,mt.OpenDate,mt.CloseDate
from ' + @dbname + ' m
inner join  dbo.MattDate md on m.MattDate = md.MattDateID ')

I would now like to put it in a CTE to use it with other database tables

; with cte as (EXECUTE ('select  mt.mattindex, sum(billfees) BillFees, m.wipbal,c.clibal, mt.number,mt.Displayname FeeEarner,MattStatus,mt.OpenDate,mt.CloseDate
from ' + @dbname + ' m
inner join  dbo.MattDate md on m.MattDate = md.MattDateID '))


Is this possible before I proceed any further and if so how?

Thanks
0
Comment
Question by:halifaxman
3 Comments
 
LVL 15

Accepted Solution

by:
Vikas Garg earned 2000 total points
ID: 40202010
Hi,

You can not use the EXECUTE withing CTE since in CTE you can only use precomputed result so what you can do is you can have table variable which will store the result of your dynamic execute query which you can use in future as CTE

DECLARE @TBL TABLE (TYOSUHDE_ID FLOAT,MAKSAVA_YKSIKKO_ID FLOAT)


INSERT INTO @TBL
EXECUTE ('SELECT TYOSUHDE_ID,MAKSAVA_YKSIKKO_ID FROM [StagingAreaKPIW].[TYOSUHDE]')

;WITH CTE AS
(
SELECT * FROM @TBL
--EXECUTE ('SELECT TYOSUHDE_ID,MAKSAVA_YKSIKKO_ID FROM [StagingAreaKPIW].[TYOSUHDE]')
)
, CTE2 AS
(
SELECT * FROM CTE WHERE MAKSAVA_YKSIKKO_ID = 5
)

SELECT * FROM CTE2
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 40202013
CTE cannot be used with EXECUTE ...

what you could do is to use a staging/temp table:

create table #t1 (name sysname)
insert into #t1
execute('select name from sysobjects')
drop table #t1
0
 
LVL 36

Expert Comment

by:ste5an
ID: 40202057
Yup, use a temporary table. E.g.
DECLARE @dbname SYSNAME = ( SELECT TOP 1
                                    D.name
                            FROM    sys.databases D
                            WHERE   D.name != 'tempdb'
                            ORDER BY D.create_date DESC
                          );

DECLARE @SQL VARCHAR(MAX) = '
INSERT INTO #Results
	SELECT	''?'' AS db_name,
		T.name ,
		T.object_id ,
		T.schema_id           
	FROM ?.sys.tables T;
';

CREATE TABLE #Results
    (
      db_name SYSNAME ,
      table_name SYSNAME ,
      object_id INT ,
      schema_id INT
    );

SET @SQL = REPLACE(@SQL, '?', @dbname);
EXECUTE (@SQL); 

SELECT  *
FROM    #Results R;

DROP TABLE #Results;

Open in new window

0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

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

A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
Ready to get certified? Check out some courses that help you prepare for third-party exams.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.
Suggested Courses

862 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