IT Nota

  • Home
  • How To
  • .NET
  • WordPress
  • Contact

How to Get Names of All Tables in SQL Server

Here’s a list of sql commands (T-SQL) to get the names of all tables, views, sprocs and triggers in SQL Server:

-- Get all Tables
SELECT name FROM sys.tables

-- Get all Views
SELECT name FROM sys.views

-- Get all Stored Procedures
SELECT name 
  FROM sys.procedures

-- Get all Triggers
SELECT name FROM sys.triggers

If you want to see all objects within the database, use the following SQL command:

SELECT name, type, type_desc
  FROM sys.objects

Try this one to also include all column names info:

SELECT * FROM sys.tables t
INNER JOIN sys.columns c
ON t.object_id = c.object_id

Further Reading

sys.objects (Transact-SQL)
How to Get Table Definition in SQL Server
How to Find All References to an Object in a SQL Server Database
How to Search for a String in All Tables in a Database
How to Find a String in SQL Server Stored Procedures

November 18, 2013 Filed Under: Database Tagged With: Microsoft SQL Server, SQL, SQL Server

Replicate Oracle Data to SQL Server

Background

HP Asset Manager SaaS data need to be transferred across customer’s internal network without too much impact on the bandwidth between the two VPNs. The agreed solution is to replicate data in Oracle to a Microsoft SQL Server database in a local network. Any new records will be inserted into the new database while existing ones will be updated.

The steps below are the quick way to setup an upsert (update and insert) SSIS package that will replicate content of a table in one database platform to another based on the last modified date on a scheduled interval. While the example is very specific, the concept can easily be adopted for other purposes.

The assumption is all Data Sources are already setup including Oracle Data Provider.

In this example, SSIS is created to transfer data from amPortfolio table, which is one of the most active tables in HP Asset Manager.

One table called QueryTime was setup just initially, this table is used to store the time of when the last query was pulled for that particular table.

CREATE TABLE QueryTime (
	Id INT IDENTITY(1,1) NOT NULL,
	TableName NVARCHAR(20) NOT NULL,
	QueryTimestamp DATETIME NOT NULL,
	
	CONSTRAINT PK_QueryTimeId PRIMARY KEY NONCLUSTERED (Id)
)

Steps

  1. Create a new DTSX package (i.e., Portfolio.dtsx). Since this will be deployed using Package Configurations, the ProtectionLevel in Properties needs to be set to DontSaveSensitive.

    SSIS Package Properties

  2. Create two variables qTimestamp and sqlPortfolio with DateTime and String data type respectively. The qTimestamp is to store the value pulled from the QueryTime table and sqlPortfolio is used to store the dynamic Oracle SQL in order to pull records since the last query timestamp.

    SSIS Setup Variables

    The initial value of sqlPortfolio in essence is a simple select statement from the amPortfolio table in the Oracle DB.

    SELECT * FROM AMPORTFOLIO

    Except with all the fields listed out, which is the better way to query.

  3. From the Toolbox, drag Execute SQL Task, Script Task, Data Flow Task, and another Execute SQL Task (1) to the Control Flow and connect the boxes by dragging the green line in the order shown below.

    SSIS Control Flow

  4. Double-click the first Execute SQL Task to open its editor. In the General section, change the Name to “Get Last QueryTime.” Select the Connection, set the ResultSet to Single row, and input the following SQLStatement to get the last query time.

    	SELECT QueryTimestamp 
        	FROM dbo.QueryTime
    	WHERE (TableName = 'AMPORTFOLIO')

    SSIS SQL Task Editor: General

  5. Still on the same active window, click on Result Set and on the right box, type in “QueryTimestamp” under the column Result Name and under Variable Name, choose the variable User::qTimestamp. Basically we take the value from column QueryTimestamp and store it in qTimestamp variable.

    SSIS SQL Task Editor: Result Set
    Click OK.

  6. Click once on the text “Script Task” and change the name to “Compose Oracle SQL” just to make it more meaningful. Double-click on the box to open the editor. In ReadOnlyVariables, if you click on the empty textbox, there should be an ellipsis (…) button. Click on the ellipsis, and select User::qTimestamp variable. Do the same for ReadWriteVariables but use variable User::sqlPortfolio this time.

    SSIS Script Task Editor

  7. Click on Edit Script… and place the code in the Main() function.

           public void Main()
           {
               string sqlCmd = string.Empty;
               string sqlPortfolio = Dts.Variables["sqlPortfolio"]
               						    .Value.ToString();
               DateTime dTimeStamp = Convert.ToDateTime(
               						   Dts.Variables["qTimestamp"]
               						      .Value);
               string timeStamp = null;
    
               if (!string.IsNullOrEmpty(dTimeStamp.ToString()))            
                 timeStamp = dTimeStamp.ToString("yyyy-MM-dd HH:mm:ss");            
               else            
                 timeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
               sqlCmd = string.Format("{0} WHERE TO_CHAR(DTLASTMODIF, 'YYYY-MM-DD HH24:MI:SS') >= '{1}' ORDER BY LPORTFOLIOITEMID",
               						   sqlPortfolio, timeStamp);
    
               // Store Oracle SQL in User:sqlPortfolio variable
               Dts.Variables["sqlPortfolio"].Value = sqlCmd;
               
               Dts.TaskResult = (int)ScriptResults.Success;
           }

    Close the window and click OK.

  8. Double-click on Data Flow Task or just click on the Data Flow tab.

  9. Open the Toolbox and from Data Flow Sources, drag OLE DB Source into the Data Flow designer surface and name it amPortfolio to reflect the table name it’s pulling data from.

  10. Open the Source Editor and select the OLE DB connection manager. Data access mode: is set to SQL command from variable and for Variable name select User::sqlPortfolio, and click OK.

  11. Next, from the Toolbox, under Data Flow Transformations drag Lookup to the surface. Open the editor and set it according to these settings:

    General

    Cache mode: Full cache
    Connection type: OLE DB connection manager
    Specify how to handle rows with no matching entries: Redirect rows to no match output

    Connection

    OLE DB connection manager: Connection to the destination database.
    Use results of an SQL query: with the following SQL statement:

    		SELECT LPORTFOLIOITEMID 
    			FROM PortfolioItem 
    		ORDER BY LPORTFOLIOITEMID

    Columns

    Drag the LPORTFOLIOITEMID from Available Input Columns on the left box to the Available Lookup Columns on the right and click OK.

    SSIS Lookup Transformation Editor

  12. Drag OLE DB Destination, name it Insert and drag OLE DB Command and name it Update.

  13. From the Lookup box, drag the green line arrow to Insert and a dialog box will pop up. Select the Lookup No Match Output from the drop down list and click OK.

    SSIS Input Output Selection

  14. Click on the Lookup box again and drag a new green line arrow to Update, and it will automatically assign the Lookup Match Output to it as shown on the picture below.

    SSIS Data Flow

  15. Double-click Insert and set Data access mode to Table or view and select the corresponding destination table from the drop-down list for Name of the table or the view. If the table does not exist yet, you can click on the button New… and SSIS will guess the table schema based on the source table.

    The auto-generated schema is generally accurate, except the table name itself, so make sure you review the SQL first before you commit by clicking OK. In this case, the table name was changed from [Insert] to [PortfolioItem].

    SSIS OLE DB Create Table Modification

    SSIS OLE DB Destination Editor

    After the correct table is selected, click OK.

  16. Double-click the Update and use the following settings:

    Connection Managers

    Select the Connection Manager from the drop-down list.

    SSIS Advanced Editor for Update

    Component Properties

    SqlCommand
    Click on the ellipsis and input an update SQL command (shortened in this example) below:

    	UPDATE [dbo].[PortfolioItem]
     	SET [BCREATEDONTHEFLY] = ?
           ,[DTLASTMODIF] = ?
           ,[ASSETTAG] = ?
    	WHERE [LPORTFOLIOITEMID] = ?

    Column Mappings

    This is the most tedious part of the setup. All the question mark in the SQL Update statement is translated into Param_# (i.e., Param_0, Param_1, Param_3, etc.) on the Destination Column. The order of the fields in the SQL statement determines the sequential number of the Param_#. So in this case, [BTCREATEDONTHEFLY] maps to Param_0 and the last field in the statement [LPORTFOLIOITEMID] is mapped to the last field in the Destination Column (i.e, Param_68). It’s crucial that you don’t miss a field or transpose the order.

    Once this part is done, click OK.

  17. Go back to the Control Flow tab and double-click on the last Execute SQL Task (Update QueryTime). This time we just need to store the new timestamp to the QueryTime table based on the latest record processed.

    SSIS Execute SQL Editor Update Query

    On the SQLStatement use the following SQL statement:

    	UPDATE dbo.QueryTime
    	SET QueryTimestamp = (SELECT MAX(DTLASTMODIF) AS Expr1
    						  FROM dbo.PortfolioItem)
    	WHERE (TableName = 'AMPORTFOLIO')

    Click OK.

Build the package and it should be ready to deploy. The final Control Flow should look like this.
SSIS Control Flow Final

Caveat

  • In order to get the package setup quickly, QueryTime table must have an initial value, at least with a table name (i.e., AMPORTFOLIO). To include all records initially, just put in 1900-01-01 and the date will be updated after the first run.

    INSERT INTO QueryTime (TableName, QuertyTimestamp)
    VALUES ('AMPORTFOLIO', '')
  • If the database has a large volume of tables, this solution might not be practical.

Further Reading

How to Create SSIS Package in Visual Studio 2017
How to Build SSIS Package for Different SQL Server Version with Visual Studio 2017 and SSDT

May 1, 2013 Filed Under: Database Tagged With: ETL, SSIS

Setting Up Oracle Data Provider for Visual Studio

In one of my SSIS 2008 applications, I had to extract data from Oracle which would be processed and dumped to SQL Server. In order to do so, SSIS will need have access to an Oracle Provider for OLE DB. I also needed to do a few simple checks here and there using SQL Plus, so there are two components I have to install to accomplish this, Oracle Data Access Components (ODAC) and Oracle Database 11g Release 2 Client for Microsoft Windows (x64), which can be downloaded from oracle.com:

The first component to install is 32-bit Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio

Oracle Data Access Components 32-bit

To make Oracle provider work within Visual Studio, use the 32-bit version. For deployment on production though, you can choose between 32-bit or 64-bit ODAC.

Oracle 11g ODAC 32-bit

For some reason, after I installed the 32-bit ODAC, I didn’t find tnsping or SQL*Plus (it turned out SQL*Plus was installed in the C:\oracle\product\11.2.0\client_1 directory, except there was no shortcut created on Windows’ Start Menu Programs List).

So to add tnsping, I installed the Oracle client and chose a different home directory, ..client_2 (but the same Oracle base directory “C:\oracle”).

Oracle 11g Client for Microsoft Windows

Oracle Client Installer Installation Type

Oracle Client Installer Base and Software Location

Oracle Client Installer Perform Prerequisite Checks

After the installation, if you open your SSIS package, you can pick Native OLE DBOracle Provider for OLE DB from SSIS Data Source Designer.

Oracle Provider Data Source

As a result of this you will have two installations of SQL*Plus in C:\oracle\product\11.2.0\client_1 and C:\oracle\product\11.2.0\client_2\bin.

Just make sure both directories are referenced in the PATH Environment Variables setting.

Downloads

Oracle Instant Client Downloads
32-bit Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio
64-bit Oracle Data Access Components (ODAC) Downloads

Further Reading

How to Build SSIS Package for Different SQL Server Version with Visual Studio 2017 and SSDT
How to Create SSIS Package in Visual Studio 2017
Oracle and Visual Studio 2012 Quickstart

December 17, 2012 Filed Under: Database Tagged With: Oracle, SQL Server

Default Ports Used by SQL Server

Microsoft SQL Server LogoThe most often asked question when configuring a firewall for SQL Server access is what ports are used by SQL Server? If your SQL Server uses default port numbers, it’s important to have TCP port 1343 & UDP port 1344 at the minimum opened. The rest port numbers are listed on the table below.

It’s important to note that a named instance will have a dynamic port number other than 1433 used and it might be better be configured to use a static port instead.

Ports Used by SQL Server Database Engine

Scenario

Port

Comments

SQL Server default instance running over TCP

TCP port 1433

This is the most common port allowed through the firewall. It applies to routine connections to the default installation of the Database Engine, or a named instance that is the only instance running on the computer. (Named instances have special considerations. See Dynamic Ports later in this topic.)

SQL Server named instances in the default configuration

The TCP port is a dynamic port determined at the time the Database Engine starts.

See the discussion below in the section Dynamic Ports. UDP port 1434 might be required for the SQL Server Browser Service when you are using named instances.

SQL Server named instances when they are configured to use a fixed port

The port number configured by the administrator.

See the discussion below in the section Dynamic Ports.

Dedicated Admin Connection

TCP port 1434 for the default instance. Other ports are used for named instances. Check the error log for the port number.

By default, remote connections to the Dedicated Administrator Connection (DAC) are not enabled. To enable remote DAC, use the Surface Area Configuration facet. For more information, see Surface Area Configuration.

SQL Server Browser service

UDP port 1434

The SQL Server Browser service listens for incoming connections to a named instance and provides the client the TCP port number that corresponds to that named instance. Normally the SQL Server Browser service is started whenever named instances of the Database Engine are used. The SQL Server Browser service does not have to be started if the client is configured to connect to the specific port of the named instance.

SQL Server instance running over an HTTP endpoint.

Can be specified when an HTTP endpoint is created. The default is TCP port 80 for CLEAR_PORT traffic and 443 for SSL_PORT traffic.

Used for an HTTP connection through a URL.

SQL Server default instance running over an HTTPS endpoint.

TCP port 443

Used for an HTTPS connection through a URL. HTTPS is an HTTP connection that uses secure sockets layer (SSL).

Service Broker

TCP port 4022. To verify the port used, execute the following query:

SELECT name, protocol_desc, port, state_desc

FROM sys.tcp_endpoints

WHERE type_desc = ‘SERVICE_BROKER’

There is no default port for SQL Server Service Broker, but this is the conventional configuration used in Books Online examples.

Database Mirroring

Administrator chosen port. To determine the port, execute the following query:

SELECT name, protocol_desc, port, state_desc FROM sys.tcp_endpoints

WHERE type_desc = ‘DATABASE_MIRRORING’

There is no default port for Database mirroring however Books online examples use TCP port 7022. It is very important to avoid interrupting an in-use mirroring endpoint, especially in high-safety mode with automatic failover. Your firewall configuration must avoid breaking quorum. For more information, see Specify a Server Network Address (Database Mirroring).

Replication

Replication connections to SQL Server use the typical regular Database Engine ports (TCP port 1433 for the default instance, etc.)

Web synchronization and FTP/UNC access for replication snapshot require additional ports to be opened on the firewall. To transfer initial data and schema from one location to another, replication can use FTP (TCP port 21), or sync over HTTP (TCP port 80) or File and Print Sharing (TCP port 137,138, or 139).

For sync over HTTP, replication uses the IIS endpoint (ports for which are configurable but is port 80 by default), but the IIS process connects to the backend SQL Server through the standard ports (1433 for the default instance.

During Web synchronization using FTP, the FTP transfer is between IIS and the SQL Server publisher, not between subscriber and IIS.

Transact-SQL debugger

TCP port 135

See Special Considerations for Port 135

The IPsec exception might also be required.

If using Visual Studio, on the Visual Studio host computer, you must also add Devenv.exe to the Exceptions list and open TCP port 135.

If using Management Studio, on the Management Studio host computer, you must also add ssms.exe to the Exceptions list and open TCP port 135. For more information, see Configure the Transact-SQL Debugger.

Further Reading

Configure the Windows Firewall to Allow SQL Server Access
TCP/IP port numbers required to communicate to SQL over a firewall

December 11, 2012 Filed Under: Database Tagged With: SQL Server

Removing _x0022_ Character Issue in SQL Server and SSIS

Just recently after an a production database upgrade to a 64-bit SQL Server 2008 R2 RTM (from SQL 2000), the same SSIS 2008 package that exports data from SQL Server 2000 to a flat file (csv/txt) started to wrap all data fields with _x0022_ hexadecimal characters.

CSV in Excel

The CSV file that was extracted is not totally worthless especially if it’s already taken hours to produce that file. We can easily have a quick workaround to fix this until the next scheduled export. By using Notepad/Notepad2 or other text editor, you want to replace the _x0022_ character with a double quotes (“).

CSV in Notepad2

Next, check your Flat File Connection Manager. Look into the Connection Managers and open the Flat File Connection Manager Editor and check the Text qualifier box. Change it to double quotes (“) from _x0022_. Click OK, save and rebuild your package.

SQL Server Flat File Connection Manager Editor

Looking further into this, it turns out the cause of the issue is the version of SQL Server in development is different than the one in production as shown in the two pictures below.

SQL Server 2008 R2 SP1 Development

Development (R2 SP1)

SQL Server 2008 R2 Production

Production (R2)

In this case, DEV is more up-to-date than PROD. After upgrading the production SQL Server to SP1, the issue was resolved.

Further Reading:
SQL Server 2008 SP1 CU 6 includes small changes to .dtsx files
SQL Server 2008 R2 SP1 Download

May 22, 2012 Filed Under: Database Tagged With: ETL, SQL Server, SSIS

« Previous Page
Buy me a coffee Support this site
Buy Me a Coffee?

Categories

  • .NET
  • Coding
  • Cybersecurity
  • Database
  • How To
  • Internet
  • Multimedia
  • Photography
  • Programming
  • Resources
  • Review
  • Tips and Tricks
  • Uncategorized
  • Use Case
  • WordPress
  • Writing

Recent Posts

  • How to View Stored Procedure Code in SQL Server
  • How to Find a String in SQL Server Stored Procedures
  • How to Remove Cached Credentials without Rebooting Windows
  • ESP Work Automation: Empowering Enterprises with Streamlined Workflows and Operational Efficiency
  • How to Search for a String in All Tables in a Database

Recent Posts

  • How to View Stored Procedure Code in SQL Server
  • How to Find a String in SQL Server Stored Procedures
  • How to Remove Cached Credentials without Rebooting Windows
  • ESP Work Automation: Empowering Enterprises with Streamlined Workflows and Operational Efficiency
  • How to Search for a String in All Tables in a Database

Tags

.NET .NET Core AdSense ASP.NET Cdonts Dll Classic ASP Code Editor ETL FSharp Genesis Framework Git Google HP Asset Manager HTML5 Hugo IIS Information Security Internet Internet Information Services iOS JAMStack Linux macOS Microsoft Microsoft SQL Server MVC PHP PowerShell Python Simple Mail Transfer Protocol Smtp Server SQL SQL Server SSIS SSMS SSRS Sublime Text Visual Studio Visual Studio Code VPN Windows Windows 8 Windows 10 Windows 2012 Windows Server

Copyright © 2011-2025 IT Nota. All rights reserved. Terms of Use | Privacy Policy | Disclosure