| Author | Topic | 
                            
                                    | maideenStarting Member
 
 
                                        10 Posts | 
                                            
                                            |  Posted - 2013-07-16 : 08:30:38 
 |  
                                            | Hi. I need help. Below dynamic Pivot working fine in exec in mssql 2005. But I need the result insert data into dynamic table then Need to export into excel. Because, the column increase time to time based on data entry. Pls help me how to export directly or insert into dynamic table. Pls help meMaideen It is my store procedure USE [collegeBac]GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[usp_pivot_by_RCVD_Dynamic]ASBEGINSET NOCOUNT ON;DECLARE @PivotColumnHeaders VARCHAR(MAX)SELECT @PivotColumnHeaders = COALESCE(@PivotColumnHeaders + ',[' + CAST(RCVDFor AS VARCHAR) + ']',    '[' + CAST(RCVDFor AS VARCHAR)+ ']' )FROM dbo.vw_PIVOT_RCVD_DISTINCTDECLARE @PivotTableSQL NVARCHAR(MAX)SET @PivotTableSQL = N'  SELECT * FROM (SELECT dbo.vwRCHeadDetails.RCDate,dbo.vwRCHeadDetails.CourseCode,dbo.vw_PIVOT_RCVD_DISTINCT.RCVDFor,  dbo.vwRCHeadDetails.Amount FROM dbo.vw_PIVOT_RCVD_DISTINCT INNER JOIN vwRCHeadDetails   ON dbo.vw_PIVOT_RCVD_DISTINCT.rcvdfor = dbo.vwRCHeadDetails.rcvdfor) AS PivotData  PIVOT ( SUM(Amount)  FOR RCVDFor IN (' + @PivotColumnHeaders + ' )) AS PivotTable 'EXECUTE(@PivotTableSQL)END |  | 
       
                            
                       
                          
                            
                                    | visakh16Very Important crosS Applying yaK Herder
 
 
                                    52326 Posts | 
                                        
                                          |  Posted - 2013-07-16 : 13:48:00 
 |  
                                          | use SELECT INTO syntax to create table on the fly------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |  
                                          |  |  | 
                            
                       
                          
                            
                                    | cjccleeStarting Member
 
 
                                    33 Posts | 
                                        
                                          |  Posted - 2013-07-16 : 14:35:53 
 |  
                                          | visakh16,  Thanks! I have similar question. I have dynamic SQL from pivot table, I want to join the result with other query. since the columns from dynamic pivot table is not fixed, I can not delare the temptable with column name, I tried your suggestion,something like this  select * into #temptable execute (@pivottableSQL)  I got error: for select into statement, verify each column has a name.  What's correct syntax for this? |  
                                          |  |  | 
                            
                       
                          
                            
                                    | James KMaster Smack Fu Yak Hacker
 
 
                                    3873 Posts | 
                                        
                                          |  Posted - 2013-07-16 : 15:50:56 
 |  
                                          | quote:SELECT INTO does not work in that context. Either you should create the table and then use the insert into ... exec syntax like in the example below, or you should modify your @pivottableSQL to insert the data into a global temp table or base table.Originally posted by cjcclee
 visakh16,  Thanks! I have similar question. I have dynamic SQL from pivot table, I want to join the result with other query. since the columns from dynamic pivot table is not fixed, I can not delare the temptable with column name, I tried your suggestion,something like this  select * into #temptable execute (@pivottableSQL)  I got error: for select into statement, verify each column has a name.  What's correct syntax for this?
 
 CREATE TABLE #temptable (col1 VARCHAR(32));DECLARE @sql NVARCHAR(4000) = 'select 1 as col1;'INSERT INTO #temptable EXEC (@sql);DROP TABLE  #temptable; |  
                                          |  |  | 
                            
                       
                          
                            
                                    | cjccleeStarting Member
 
 
                                    33 Posts | 
                                        
                                          |  Posted - 2013-07-16 : 16:35:35 
 |  
                                          | Thank you! The columns returned from pivot table are not fixed.It maybe have col1, col2, col3 or it maybe have col1,col2,col3,col4 or more. If create temp table, I do not know how many columns to be declared.How can create temp table on the fly using results from execute dynamic SQL? quote:Originally posted by James K
 
 quote:SELECT INTO does not work in that context. Either you should create the table and then use the insert into ... exec syntax like in the example below, or you should modify your @pivottableSQL to insert the data into a global temp table or base table.Originally posted by cjcclee
 visakh16,  Thanks! I have similar question. I have dynamic SQL from pivot table, I want to join the result with other query. since the columns from dynamic pivot table is not fixed, I can not delare the temptable with column name, I tried your suggestion,something like this  select * into #temptable execute (@pivottableSQL)  I got error: for select into statement, verify each column has a name.  What's correct syntax for this?
 
 CREATE TABLE #temptable (col1 VARCHAR(32));DECLARE @sql NVARCHAR(4000) = 'select 1 as col1;'INSERT INTO #temptable EXEC (@sql);DROP TABLE  #temptable; 
 |  
                                          |  |  | 
                            
                       
                          
                            
                                    | MuMu88Aged Yak Warrior
 
 
                                    549 Posts | 
                                        
                                          |  Posted - 2013-07-16 : 21:16:41 
 |  
                                          | Try the modifications shown in red below: quote:[/size=2]Originally posted by maideen
 Hi. I need help. Below dynamic Pivot working fine in exec in mssql 2005. But I need the result insert data into dynamic table then Need to export into excel. Because, the column increase time to time based on data entry. Pls help me how to export directly or insert into dynamic table. Pls help meMaideen It is my store procedure USE [collegeBac]GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[usp_pivot_by_RCVD_Dynamic]ASBEGINSET NOCOUNT ON;DECLARE @PivotColumnHeaders VARCHAR(MAX)SELECT @PivotColumnHeaders = COALESCE(@PivotColumnHeaders + ',[' + CAST(RCVDFor AS VARCHAR) + ']',    '[' + CAST(RCVDFor AS VARCHAR)+ ']' )FROM dbo.vw_PIVOT_RCVD_DISTINCTDECLARE @PivotTableSQL NVARCHAR(MAX)SET @PivotTableSQL = N'  SELECT * into #temp FROM (SELECT dbo.vwRCHeadDetails.RCDate,dbo.vwRCHeadDetails.CourseCode,dbo.vw_PIVOT_RCVD_DISTINCT.RCVDFor,  dbo.vwRCHeadDetails.Amount FROM dbo.vw_PIVOT_RCVD_DISTINCT INNER JOIN vwRCHeadDetails   ON dbo.vw_PIVOT_RCVD_DISTINCT.rcvdfor = dbo.vwRCHeadDetails.rcvdfor) AS PivotData  PIVOT ( SUM(Amount)  FOR RCVDFor IN (' + @PivotColumnHeaders + ' )) AS PivotTable 'EXECUTE(@PivotTableSQL)END
 
 |  
                                          |  |  | 
                            
                       
                          
                            
                                    | visakh16Very Important crosS Applying yaK Herder
 
 
                                    52326 Posts | 
                                        
                                          |  Posted - 2013-07-17 : 02:08:36 
 |  
                                          | quote:This will make # tales out of scope once outside the dynamic sql. So I think you might need to use ## tables instead.Also beware of issues due to concurrent execution etc.------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogsOriginally posted by MuMu88
 Try the modifications shown in red below:
 quote:[/size=2]Originally posted by maideen
 Hi. I need help. Below dynamic Pivot working fine in exec in mssql 2005. But I need the result insert data into dynamic table then Need to export into excel. Because, the column increase time to time based on data entry. Pls help me how to export directly or insert into dynamic table. Pls help meMaideen It is my store procedure USE [collegeBac]GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[usp_pivot_by_RCVD_Dynamic]ASBEGINSET NOCOUNT ON;DECLARE @PivotColumnHeaders VARCHAR(MAX)SELECT @PivotColumnHeaders = COALESCE(@PivotColumnHeaders + ',[' + CAST(RCVDFor AS VARCHAR) + ']',    '[' + CAST(RCVDFor AS VARCHAR)+ ']' )FROM dbo.vw_PIVOT_RCVD_DISTINCTDECLARE @PivotTableSQL NVARCHAR(MAX)SET @PivotTableSQL = N'  SELECT * into #temp FROM (SELECT dbo.vwRCHeadDetails.RCDate,dbo.vwRCHeadDetails.CourseCode,dbo.vw_PIVOT_RCVD_DISTINCT.RCVDFor,  dbo.vwRCHeadDetails.Amount FROM dbo.vw_PIVOT_RCVD_DISTINCT INNER JOIN vwRCHeadDetails   ON dbo.vw_PIVOT_RCVD_DISTINCT.rcvdfor = dbo.vwRCHeadDetails.rcvdfor) AS PivotData  PIVOT ( SUM(Amount)  FOR RCVDFor IN (' + @PivotColumnHeaders + ' )) AS PivotTable 'EXECUTE(@PivotTableSQL)END
 
 
 |  
                                          |  |  | 
                            
                       
                          
                            
                                    | maideenStarting Member
 
 
                                    10 Posts | 
                                        
                                          |  Posted - 2013-07-18 : 00:47:59 
 |  
                                          | Thanks Mr. visakh16. Now SP works fineProblem solves using "Select into tablename"Regards Maideen |  
                                          |  |  | 
                            
                       
                          
                            
                                    | maideenStarting Member
 
 
                                    10 Posts | 
                                        
                                          |  Posted - 2013-07-18 : 00:54:00 
 |  
                                          | Hi AllThere is one problem in SP when execute. I have added the date and export into Excel.Must declare the scalar variable "@FDate".Here is my SP. Pls advice where I did wrong...MaideenSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[usp_pivot_by_RCVD_Dynamic]@FDate AS DATETIME,@TDate AS DATETIMEASBEGINSET NOCOUNT ON;DECLARE @PivotColumnHeaders VARCHAR(MAX)SELECT @PivotColumnHeaders = COALESCE(@PivotColumnHeaders + ',[' + CAST(RCVDFor AS VARCHAR) + ']',    '[' + CAST(RCVDFor AS VARCHAR)+ ']' )FROM dbo.vw_PIVOT_RCVD_DISTINCTDECLARE @PivotTableSQL NVARCHAR(MAX)SET @PivotTableSQL = N'  SELECT * into tbl_RCVDfor_Rajan FROM (SELECT dbo.vwRCHeadDetails.RCDate,dbo.vwRCHeadDetails.CourseCode,dbo.vw_PIVOT_RCVD_DISTINCT.RCVDFor,  dbo.vwRCHeadDetails.Amount FROM dbo.vw_PIVOT_RCVD_DISTINCT INNER JOIN vwRCHeadDetails   ON dbo.vw_PIVOT_RCVD_DISTINCT.rcvdfor = dbo.vwRCHeadDetails.rcvdforWHERE dbo.vwRCHeadDetails.RCDate >=@FDate and dbo.vwRCHeadDetails.RCDate <=@TDate) AS PivotData  PIVOT ( SUM(Amount)  FOR RCVDFor IN (' + @PivotColumnHeaders + ' )) AS PivotTable ' EXECUTE(@PivotTableSQL)insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',     'Excel 8.0;Database=D:\testing.xls;',     'SELECT * FROM [Sheet1]') select * from tbl_RCVDfor_Rajan Drop Table tbl_RCVDfor_RajanSelect 'Successfully Exported to Excel'END |  
                                          |  |  | 
                            
                       
                          
                            
                                    | visakh16Very Important crosS Applying yaK Herder
 
 
                                    52326 Posts | 
                                        
                                          |  Posted - 2013-07-18 : 01:29:51 
 |  
                                          | The variable @Fdate will be out of scope when used inside dynamic sql.so it should be this SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[usp_pivot_by_RCVD_Dynamic]@FDate AS DATETIME,@TDate AS DATETIMEASBEGINSET NOCOUNT ON;DECLARE @PivotColumnHeaders VARCHAR(MAX)SELECT @PivotColumnHeaders = COALESCE(@PivotColumnHeaders + ',[' + CAST(RCVDFor AS VARCHAR) + ']','[' + CAST(RCVDFor AS VARCHAR)+ ']' )FROM dbo.vw_PIVOT_RCVD_DISTINCTDECLARE @PivotTableSQL NVARCHAR(MAX)SET @PivotTableSQL = N'SELECT * into tbl_RCVDfor_Rajan FROM (SELECT dbo.vwRCHeadDetails.RCDate,dbo.vwRCHeadDetails.CourseCode,dbo.vw_PIVOT_RCVD_DISTINCT.RCVDFor,dbo.vwRCHeadDetails.Amount FROM dbo.vw_PIVOT_RCVD_DISTINCT INNER JOIN vwRCHeadDetails ON dbo.vw_PIVOT_RCVD_DISTINCT.rcvdfor = dbo.vwRCHeadDetails.rcvdforWHERE dbo.vwRCHeadDetails.RCDate >= ''' + @FDate + ''' and dbo.vwRCHeadDetails.RCDate <= ''' + @TDate+ ''') AS PivotDataPIVOT ( SUM(Amount) FOR RCVDFor IN (' + @PivotColumnHeaders + ' )) AS PivotTable 'EXECUTE(@PivotTableSQL)insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;', 'SELECT * FROM [Sheet1]') select * from tbl_RCVDfor_Rajan Drop Table tbl_RCVDfor_RajanSelect 'Successfully Exported to Excel'END------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |  
                                          |  |  | 
                            
                       
                          
                            
                                    | maideenStarting Member
 
 
                                    10 Posts | 
                                        
                                          |  Posted - 2013-07-18 : 20:16:32 
 |  
                                          | Mr.VisakhThank you. It work fine. But If I define FDate and TDate as DateTimeThe error is "Conversion failed when converting datetime from character string. "But If I define FDate and TDate as nvarchar(20) It is work fine No error.Is there any problem?Maideen |  
                                          |  |  | 
                            
                       
                          
                            
                                    | bandiMaster Smack Fu Yak Hacker
 
 
                                    2242 Posts | 
                                        
                                          |  Posted - 2013-07-19 : 00:49:15 
 |  
                                          | -- do the following modificationALTER PROCEDURE [dbo].[usp_pivot_by_RCVD_Dynamic]@FDate AS VARCHAR(50),@TDate AS VARCHAR(50)AS--Chandu |  
                                          |  |  | 
                            
                       
                          
                            
                                    | visakh16Very Important crosS Applying yaK Herder
 
 
                                    52326 Posts | 
                                        
                                          |  Posted - 2013-07-19 : 00:56:27 
 |  
                                          | quote:You should always try to use proper datatype for your fields/parameters. If they're accepting date values, the datatype has to be datetime or dateThe error occurs when value you passed to variable cannot be correctly interpreted as a valid date value based on server locale settings. Safe bet is to use unambiguos iso format.http://visakhm.blogspot.com/2011/12/why-iso-format-is-recommended-while.html------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogsOriginally posted by maideen
 Mr.VisakhThank you. It work fine. But If I define FDate and TDate as DateTimeThe error is "Conversion failed when converting datetime from character string. "But If I define FDate and TDate as nvarchar(20) It is work fine No error.Is there any problem?Maideen
 
 |  
                                          |  |  | 
                            
                            
                                |  |