Thursday, May 30, 2013

SQL SERVER – Simple Example of Recursive CTE

Recursive is the process in which the query executes itself. It is used to get results based on the output of base query. We can use CTE as Recursive CTE (Common Table Expression). You can read my previous articles about CTE by searching at http://search.SQLAuthority.com .
Here, the result of CTE is repeatedly used to get the final resultset. The following example will explain in detail where I am using AdventureWorks database and try to find hierarchy of Managers and Employees.
USE AdventureWorks
GO
WITH Emp_CTE AS (SELECT EmployeeIDContactIDLoginIDManagerIDTitleBirthDateFROM HumanResources.EmployeeWHERE ManagerID IS NULLUNION ALLSELECT e.EmployeeIDe.ContactIDe.LoginIDe.ManagerIDe.Title,e.BirthDateFROM HumanResources.Employee eINNER JOIN Emp_CTE ecte ON ecte.EmployeeID e.ManagerID)SELECT *FROM Emp_CTE
GO
In the above example Emp_CTE is a Common Expression Table, the base record for the CTE is derived by the first sql query before UNION ALL. The result of the query gives you the EmployeeID which don’t have ManagerID.
Second query after UNION ALL is executed repeatedly to get results and it will continue until it returns no rows. For above e.g. Result will have EmployeeIDs which have ManagerID (ie, EmployeeID of the first result).  This is obtained by joining CTE result with Employee table on columns EmployeeID of CTE with ManagerID of table Employee.
This process is recursive and will continue till there is no ManagerID who doesn’t have EmployeeID

Wednesday, May 29, 2013

Add Identity Column to Table Based on Order of Another Column

http://blog.sqlauthority.com/2013/05/30/sql-server-add-identity-column-to-table-based-on-order-of-another-column/

I already have existing table and the table already have fewer columns. The table does not have identity column and I would like to add an identity column to this table. The problem is that every time when I try to add an identity column to the table, it adds the value based on the default order of the table. I would like to add the identity value based on the order sequence of another column from the table. Do you have any alternative to it. To illustrate my problem here is the simple script based on my table schema. My table also do not have any index as of now.
USE tempdb
GO
-- Create TableCREATE TABLE TestTable (Col1 INT, Col2 VARCHAR(100))GO-- Insert DataINSERT INTO TestTable (Col1, Col2)VALUES (33, 'Pinal');INSERT INTO TestTable (Col1, Col2)VALUES (22, 'Nupur');INSERT INTO TestTable (Col1, Col2)VALUES (11, 'Shaivi');GO-- Select DataSELECT *FROM TestTable
GO
-- Add Identity ColumnALTER TABLE TestTableADD ID INT IDENTITY(1, 1)GO-- Select DataSELECT *FROM TestTable
GO
-- Clean upDROP TABLE TestTable
GO

Here is the result set of the query above. Currently the result is ordered by the column Col1 DESC but ideally I would like to get the result ordered by Col1 but in ASC order.
Is there any workaround to do the same?”
As I said I find this question very interesting and I was able to come up with the solution as well fairly quickly as the user had not created an index on the table. I quickly created clustered index in ASC order on Col1 and it ordered the table as expected and later added the identity column there. Let us see the script to get the desired result.
USE tempdb
GO
-- Create TableCREATE TABLE TestTable (Col1 INT, Col2 VARCHAR(100))GO-- Insert DataINSERT INTO TestTable (Col1, Col2)VALUES (33, 'Pinal');INSERT INTO TestTable (Col1, Col2)VALUES (22, 'Nupur');INSERT INTO TestTable (Col1, Col2)VALUES (11, 'Shaivi');GO-- Select DataSELECT *FROM TestTable
GO
-- Create Clustered Index on Column IDCREATE CLUSTERED INDEX IX_TestTable ON dbo.TestTable(Col1 ASC)GO-- Add Identity ColumnALTER TABLE TestTableADD ID INT IDENTITY(1, 1)GO-- Select DataSELECT *FROM TestTable
GO
-- Clean upDROP TABLE TestTable
GO

Above script will produce following answer which user is expecting:
Now here is my question back to, this was fairly simple for me to do as there was no index created on the table. I was able to create clustered index on the column and get the desired result. However, what will be the alternative solution to this question if the clustered index is already created on the table and there was no option to modify the same. Another alternative solution would be to drop the table and do processing but that is never a good solution as well, it is not possible if there are foreign keys exists on the table

Tuesday, May 28, 2013

SSRS - Creating basic Report

http://www.accelebrate.com/sql_training/ssrs_2008_tutorial.htm


Chapter 17: Reporting
Services
In this chapter:

The Reporting Services Architecture
Using Report Designer
Publishing a Report
Using Report Builder
Using Report Manager
Files needed:
ProductReport1.zip
ProductReport2.zip
AWSales.zip
Reporting Services
17-2 Introduction to SQL Server 2008 Copyright © 2009 Accelebrate, Inc
For many years, SQL Server did not have a good answer for creating attractive
reports that summarize information in ways that make sense to business users.
Finally, Microsoft shipped SQL Server Reporting Services. Like Notification
Services, Reporting Services was originally an add-on for SQL Server 2000, and now
it’s a part of the core product. In this chapter, you’ll learn how to use Reporting
Services to produce your own reports.
The Reporting Services Architecture
Reporting Services has a quite a few components that work together seamlessly to
provide a complete reporting solution. The full Reporting Services architecture
includes development tools, administration tools, and report viewers. There are a
number of ways to get to Reporting Services programmatically, including URL,
SOAP and WMI interfaces.
Figure 17-1 shows a simplified diagram of the main Reporting Services components
that we’ll be using in this chapter.
Figure 17-1: Report Server architecture
In this chapter you’ll learn about these components:
Report Server is the core engine that drives Reporting Services.
Report Manager is a Web-based administrative interface for Reporting
Services.

Report Designer is a developer tool for building complex reports.
Report Builder is a simplified end-user tool for building reports.
Using
Report Designer
Copyright © 2009 Accelebrate, Inc. Introduction to SQL Server 2008 17-3
The Report Server database stores report definitions. Reports themselves can
make use of data from many different data sources.

Using Report Designer
Reporting Services includes two tools for creating reports:
Report Designer can create reports of any complexity that Reporting Services
supports, but requires you to understand the structure of your data and to be
able to navigate the Visual Studio user interface.

Report Builder provides a simpler user interface for creating ad hoc reports,
directed primarily at business users rather than developers. Report Builder
requires a developer or administrator to set up a data model before end users
can create reports.
We’ll start our tour of Reporting Services with Report Designer. Report Designer
runs inside the Business Intelligence Development Studio shell, and offers several
ways to create reports. You can either use the Report Wizard to quickly create a
report, or you can use a set of design tools to build a report from scratch. You can
also use the design tools to modify a report created with the wizard.

Using the Report Wizard
The easiest way to create a report in Report Designer is to use the Report Wizard.
Like all wizards, the Report Wizard walks you through the process in step-by-step
fashion. You can make the following choices in the wizard:
The data source to use
The query to use to retrieve data
Whether to use a tabular or matrix layout for the report
How to group the retrieved data
What visual style to use
Where to deploy the finished report
Try It!
To create a simple report using the Report Wizard, follow these steps:
1. Launch Business Intelligence Development Studio.
2. Select File
􀁦 New 􀁦 Project.
3. Select the Business Intelligence Projects project type.
4. Select the Report Server Project Wizard template.

Reporting Services
17-4 Introduction to SQL Server 2008 Copyright © 2009 Accelebrate, Inc
5. Name the new project ProductReport1 and pick a convenient location to save it
in.
6. Click OK.
7. Read the first page of the Report Wizard and click Next.
8. Name the new data source
AdventureWorksDS.
9. Click the Edit button.
10. Log on to your test server.
11. Select the
AdventureWorks2008 database.
12. Click OK.
13. Click the Credentials button.
14. Select Use Windows Authentication.
15. Click OK.
16. Check the Make This a Shared Data Source checkbox. This will make this
particular data source available to other Reporting Services applications in the
future.
17. Click Next.
18. Click the Query Builder button.
19. If the full query designer interface does not display by default, click the query
designer toolbar button at the far left end of the toolbar. Figure 17-2 shows the
full query designer interface.

Using
Report Designer
Copyright © 2009 Accelebrate, Inc. Introduction to SQL Server 2008 17-5
Figure 17-2: Query Builder
20. Click the Add Table toolbar button.
21. Select the
Product table and click Add.
22. Click Close.
23. Check the
Name, ProductNumber, Color, and ListPrice columns.
24. Click OK.
25. Click Next.
26. Select the Tabular layout and click Next.
27. Move the
Color column to the Group area, and the other three columns to the
Detail area, as shown in Figure 17-3.

Figure17-3: Grouping columns in the report
28. Click Next.
Reporting Services
17-6 Introduction to SQL Server 2008 Copyright © 2009 Accelebrate, Inc
29. Select the Stepped layout and click Next.
30. Select the Ocean style and click Next.
31. Accept the default deployment location and click Next.
32. Name the report ProductReport1.
33. Check the Preview Report checkbox.
34. Click Finish.
Figure 17-4 shows the finished report, open in Report Designer.
Figure 17-4: Report created by the Report Wizard
Figure 17-4 shows the main features of Report Designer:
The Report Data window shows the data that is available to the report.
The main design window lets you view the report itself. You can see a
preview of the report, work with the report in a layout designer, or work with
the query that returns the data for the report.

The Solution Explorer, Output, and Properties windows are the standard
Visual Studio windows.

Using
Report Designer
Copyright © 2009 Accelebrate, Inc. Introduction to SQL Server 2008 17-7
Modifying a Report
Now that you’ve created a report with the Report Wizard, you can modify it with
the Report Designer. If you’ve used any sort of visual report design tool in the past,
you should have no problem making changes here. Among the possibilities here:
You can change the available data or the sort order for the report by
modifying the query.

You can resize or rearrange controls on the Design tab.
You can use the Properties window to change properties of individual
controls including their font, alignment, colors, and so on.

Try It!
To modify the report that you just created, follow these steps:
1. Click the Design tab to make the report editable.
2. In the Report Data window, right-click on DataSet1 and select Dataset
Properties.
3. In the Dataset Properties window, click the Query Designer button.
4. Select a Descending sort type for the
ListPrice column and click OK.
5. Click OK.
6. Click in the textbox at the top of the report, where the report name is displayed.
7. Click a second time in the textbox to put it in edit mode and change the value
of this control to
Products By Color.
8. Click on the header for the
Product column.
9. Place the cursor between the column selectors above the
Name and Product
Number
columns to display a double-headed arrow. Hold down the mouse
button and drag the cursor to the right to widen the
Name column.
10. Place the cursor between the column selectors above the
Product Number
and
ListPrice columns to display a double-headed arrow. Hold down the
mouse button and drag the cursor to the right to widen the
Product Number
column.
11. Click on the Preview tab to view the modified report, as shown in Figure 17-5.
Reporting Services
17-8 Introduction to SQL Server 2008 Copyright © 2009 Accelebrate, Inc
Figure 17-5: Modified product report
Designing a Report From Scratch
You can also use Report Designer to build your own reports starting from scratch. In
general, you’ll follow these steps to create a report:
1. Create a Report project in Business Intelligence Design Studio or open an
existing Report project.
2. Add a report to the project.
3. Create one or more datasets for the report.
4. Build the report layout.
Try It!
To create a fresh report in Report Designer, follow these steps:
1. Select File
􀁦 New 􀁦 Project.
Using
Report Designer
Copyright © 2009 Accelebrate, Inc. Introduction to SQL Server 2008 17-9
2. Select the Business Intelligence Projects project type.
3. Select the Report Server Project template.
4. Name the new report
ProductReport2 and pick a convenient location to save
it in.
5. Right-click on the Reports node in Solution Explorer and select Add
􀁦 New
Item.
6. Select the Report template.
7. Name the new report
ProductReport2.rdl and click Add.
8. In the Report Data window, select New
􀁦 Data Source.
9. Name the new Data Source
AdventureWorksDS.
10. Select the Embedded Connection option and click on the Edit button.
11. Connect to your test server and choose the
AdventureWorks2008 database.
12. Click OK.
13. Click OK again to create the data source.
14. In the Report Data window, select New
􀁦 Dataset.
15. Name the dataset
dsLocation.
16. Click the Query Designer button.
17. If the full Query Designer does not appear, click on the Edit As Text button.
18. Click the Add Table button.
19. Select the
Location table.
20. Click Add.
21. Click Close.
22. Check the boxes for the
Name and CostRate columns.
23. Sort the dataset in ascending order by
Name and click OK.
24. Click OK again to create the dataset.
25. Open the toolbox window (View
􀁦 Toolbox).
26. Double-click the Table control.
27. Switch back to the Report Data window.
28. Expand the dataset to show the column names.
29. Drag the
Name field and drop it in the first column of the table control on the
design tab.
30. Drag the
CostRate field from the Report Data window and drop it in the
second column of the table control.
31. Place the cursor between the column selectors above the
Name and CostRate
columns to display a double-headed arrow. Hold down the mouse button and
drag the cursor to the right to widen the
Name column.
32. Figure 17-6 shows the report in Design view.

Reporting Services
17-10 Introduction to SQL Server 2008 Copyright © 2009 Accelebrate, Inc
Figure 17-6: Designing a report from scratch
33. Select the Preview tab to see the report with data.
Publishing a Report
Creating reports in Business Intelligence Development Studio is good for
developers, but it doesn’t help users at all. In order for the reports you build to be
available to others, you must publish them to your Reporting Services server. To
publish a report, you can use the Build and Deploy menu items in Business
Intelligence Development Studio. Before you do this, you need to check the project’s
configuration to make sure that you’ve selected an appropriate server for the
deployment.
Publishing
a Report
Copyright © 2009 Accelebrate, Inc. Introduction to SQL Server 2008 17-11
Try It!
You can publish any report, but the first report you created is probably more
visually interesting at this point. To publish the first report, follow these steps:
1. Select File
􀁦 Recent Projects and choose your ProductReport1 project.
2. Select Project
􀁦 ProductReport1 Properties.
3. Click the Configuration Manager button.
4. Fill in the Target Server URL for your Report Server. If you’re developing on
the same computer where Reporting Services is installed, and you installed in
the default configuration, this will be
http://localhost/ReportServer.
Figure 17-7 shows the completed Property Pages.

Figure 17-7: Setting report project properties
5. Click OK.
6. Select Build
􀁦 Deploy ProductReport1. The Output Window will track the
progress of BIDS in deploying your report, as shown in Figure 17-8. Depending
on the speed of your computer, building the report may take some time.

Reporting Services
17-12 Introduction to SQL Server 2008 Copyright © 2009 Accelebrate, Inc
Figure 17-8: Deploying a report
7. Launch a web browser and enter the address
http://localhost/reports.
8. It may take several minutes for the web page to display; Reporting Services
goes to sleep when it hasn’t been used for a while and can take a while to spin
up to speed. Figure 17-9 shows the result.

Using
Report Builder
Copyright © 2009 Accelebrate, Inc. Introduction to SQL Server 2008 17-13
Figure 17-9: The Report Manager.
9. Click the link for the ProductReport1 folder.
10. Click the link for the ProductReport1 report.
Using Report Builder
Report Designer gives you one way to create reports for Reporting Services, but it’s
not the only way. SQL Server 2008 also includes a tool directed at end users named
Report Builder. Unlike Report Designer, which is aimed at Developers, Report
Builder presents a simplified view of the report-building process and is intended for
business analysts and other end users.
Building a Data Model
Report Builder doesn’t let end users explore all of a SQL Server database. Instead, it
depends on a data model: a preselected group of tables and relationships that a
developer has identified as suitable for end-user reporting. To build a data model,
you use Business Intelligence Development Studio. Data models contain three
things:
Data Sources connect the data model to actual data.
Data Source Views draw data from data sources.
Report Models contain entities that end users can use on reports.
Try It!
To create a data model, follow these steps:
1. If it’s not already open, launch Business Intelligence Development Studio
2. Select File
􀁦 New 􀁦 Project.
3. Select the Business Intelligence Projects project type.
4. Select the Report Model Project template.
5. Name the new project
AWSales and save it in a convenient location.
6. Click OK.
7. Right-click on Data Sources in Solution Explorer and select Add New Data
Source.
8. Read the first page of the Add New Data Source Wizard and click Next.
9. Click New.
10. In the Connection Manager dialog box connect to the
AdventureWorks2008
database on your test server and click OK.
11. Click Next.
12. Name the new data source AdventureWorks and click Finish.
Reporting Services
17-14 Introduction to SQL Server 2008 Copyright © 2009 Accelebrate, Inc
13. Right-click on Data Source Views in Solution Explorer and select Add New
Data Source View.
14. Read the first page of the Add New Data Source View Wizard and click Next.
15. Select the
AdventureWorks data source and click Next.
16. Select the
Product(Production) table and click the > button to move it to
the Included Objects listbox.
17. Select the
SalesOrderDetail(Sales) table and click the > button to move
it to the Included Objects listbox.
18. Click the Add Related Tables button.
19. Click Next.
20. Click Finish.
21. Right-click on Report Models in Solution Explorer and select Add New Report
Model.
22. Read the first page of the Report Model Wizard and click Next.
23. Select the
Adventure Works2008 data source view and click Next.
24. Keep the default rules selection, as shown in Figure 17-10, and click Next.

Using
Report Builder
Copyright © 2009 Accelebrate, Inc. Introduction to SQL Server 2008 17-15
Figure 17-10: Creating entities for end-user reporting
25. Choose the Update Statistics option and click Next.
26. Click Run to complete the wizard.
27. Click Finish. If you get a warning that a file was modified outside the source
editor, click Yes.
28. Select Build
􀁦 Deploy AWSales to deploy the report model to the local
Reporting Services server.

Building a Report
Report Builder itself is a ClickOnce Windows Forms application. That means that it’s
a Windows application that end users launch from their web browser, but it never
gets installed on their computer, so they don’t need any local administrator rights on
their computer to run it. To get started with Report Builder, browse to your
Reporting Services home page. Typically, this will have a URL such as
Reporting Services
17-16 Introduction to SQL Server 2008 Copyright © 2009 Accelebrate, Inc
http://
ServerName/Reports (or http://localhost/Reports if you're
running the browser on the same box with SQL Server 2008 itself). Figure 17-11
shows the Reporting Services home page.

Figure 17-11: Reporting Services home page
To run Report Builder, click the Report Builder link in the home page menu bar.
Report Builder will automatically load up all of the available report models and wait
for you to choose one to build a report from.
Try It!
1. Open a browser window and navigate to
http://localhost/Reports (or
to the appropriate Report Server URL if you’re not working on the report
server).
2. Click the Report Builder link.
3. Depending on your operating system, you may have to confirm that you want
to run the application.

Using
Report Builder
Copyright © 2009 Accelebrate, Inc. Introduction to SQL Server 2008 17-17
4. After Report Builder is loaded, select the AdventureWorks2008 report model
and the table report layout. Click OK. Figure 17-12 shows the new blank report
that Report Builder will create.
Figure 17-12: New report in Report Builder
The Explorer window to the left of the design surface shows all of
the tables in the report model. Beneath that, the Fields window
shows the attributes in the currently-selected entity. Note that not
everything in this window is a column in the table: the report
model also contains aggregate entities such as Total Safety Stock
Level and automatically calculated fields.
5. Select the
Product table.
6. Drag the
Name field and drop it in the area labeled Drag and Drop Column
Fields.
7. Click on
Special Offer Products in the Explorer window to show related
child tables.
8. Click on
Sales Order Details.
9. Drag the
Total Order Qty field and drop it to the right of the Name field.
10. Click where it says Click to Add Title and type
Product Sales.
Reporting Services
17-18 Introduction to SQL Server 2008 Copyright © 2009 Accelebrate, Inc
11. Click the Run Report button to produce the report shown in Figure 17-13.
Figure 17-13: Report in Report Builder
12. Click the Sort and Group toolbar button.
13. Select to sort by Total Order Qty descending.
14. Click OK.
15. Select File
􀁦 Save.
16. Name the new report Product Sales.
17. Click Save. This will publish the report back to the Reporting Services server
that you originally downloaded Report Builder from.

Using
Report Manager
Copyright © 2009 Accelebrate, Inc. Introduction to SQL Server 2008 17-19
Using Report Manager
The Web home page for Reporting Services provides a complete interface for
managing reports (as well as other objects such as data sources and models) after
they are created. This interface, known as Report Manager, is intended primarily for
database administrators, but as a developer you should know about its capabilities
for managing and modifying reports.
When you click on a report in Report Manager, you’ll see the report’s data, as shown
in Figure 17-14.
Figure 17-14: Report in Report Manager
Note that reports in Report Manager open in a tabbed interface. The four tabs allow
you to perform various functions:
View allows you to see the current data in the report.
Reporting Services
17-20 Introduction to SQL Server 2008 Copyright © 2009 Accelebrate, Inc
Properties lets you adjust such things as the report’s name, data source,
security credentials, caching, and end-user security.

History shows you saved snapshots of the report.
Subscriptions lets you create subscriptions to the report. Subscriptions allow
you to set up periodic delivery of reports to end users by e-mail or file share.

Printing and Exporting Reports
When viewing reports in the Report Manager, users can print the reports directly
from their browser. The print button in the report toolbar utilizes an ActiveX control
for client-side printing. The first time this button is clicked on a given computer, the
user is prompted to install the ActiveX control, as in Figure 17-15. After that, the
standard Windows print dialog box is displayed for the user to select a printer and
paper size, etc.
Figure 17-15: ActiveX install prompt.
Users can also export the report into any of several handy formats. Table 17-1 lists
the available export formats.
Export Format Handles
XML Creates a data file in XML format.
CSV Creates a comma-delimited text file of report data.
PDF Creates an Adobe Acrobat file with the formatted report.
MHTML Creates a Web Archive file with the formatted report.
EXCEL Creates a MS Excel spreadsheet with the formatted
report.
TIFF Creates a TIFF graphic of the formatted report.
Word Creates a MS Word document with the formatted report.
Table 17-1: Export Formats
Exercises
Copyright © 2009 Accelebrate, Inc. Introduction to SQL Server 2008 17-21
Exercises
Use Report Builder to create a report from the
AdventureWorks2008 data model
showing the minimum and maximum order quantity for orders taken by each
salesperson in the company. You’ll find the necessary data in the

SalesOrderHeader
and SalesOrderDetail tables.
Reporting Services
17-22 Introduction to SQL Server 2008 Copyright © 2009 Accelebrate, Inc
Solutions to Exercises
1. Open a browser window and navigate to
http://localhost/Reports (or
to the appropriate Report Server URL if you’re not working on the report
server).
2. Click the Report Builder link.
3. Select the
AdventureWorks2008 report model and the table report layout.
4. Click OK.
5. Select the
Sales Order Header table.
6. Drag the
Sales Person ID field and drop it in the area labeled Drag and
Drop Column Fields.
7. Click on
Sales Order Details in the Explorer window.
8. Expand the
Total Order Qty field in the Fields window to show the
alternative fields beneath it.
9. Drag the
Min Order Qty field and drop it to the right of the Name field.
10. Drag the
Max Order Qty field and drop it to the right of the Min Order
Qty
field.
11. Click where it says Click to Add Title and type
Sales Performance.
12. Click the Run Report button to produce the report shown in Figure 17-15.

Solutions
to Exercises
Copyright © 2009 Accelebrate, Inc. Introduction to SQL Server 2008 17-23
Figure 17-15: Sales performance report


Complete Tutorial - 

Sunday, May 26, 2013

INSERT data from Stored Procedure to Table

http://blog.sqlauthority.com/2013/05/27/sql-server-how-to-insert-data-from-stored-procedure-to-table-2-different-methods/

“How do I insert the results of the stored procedure in my table?”
This question has two fold answers – 1) When the table is already created and 2) When the table is to be created run time. In this blog post we will explore both the scenarios together.
However, first let us create a stored procedure which we will use for our example.
CREATE PROCEDURE GetDBNamesAS
SELECT
name, database_idFROM sys.databases
GO
We can execute this stored procedure using the following script.
EXEC GetDBNames
Now let us see two different scenarios where we will insert the data of the stored procedure directly into the table.
1) Schema Known – Table Created Beforehand
If we know the schema of the stored procedure resultset we can build a table beforehand and execute following code.
CREATE TABLE #TestTable ([name] NVARCHAR(256), [database_ID] INT);INSERT INTO #TestTableEXEC GetDBNames-- Select TableSELECT *FROM #TestTable;
The disadvantage of this code is that if due to any reason the stored procedure returns more or less columns it will throw an error.
2) Unknown Schema – Table Created at Runtime
There are cases when we do know the resultset of the stored procedure and we want to populate the table based of it. We can execute following code.
SELECT * INTO #TestTableT FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;','EXEC tempdb.dbo.GetDBNames')-- Select TableSELECT *FROM #TestTableT;
The disadvantage of this code is that it bit complicated but it usually works well in the case of the column names are not known.
Just note that if you are getting error in this method enable ad hoc distributed queries by executing following query in SSMS.
sp_configure 'Show Advanced Options', 1
GO
RECONFIGUREGOsp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGUREGO