A union statement takes two or more SELECT statements, combines them, and returns an output. In order to be UNION compatible the following conditions must be met in the tables within SQL Server Management Studio. 1. Tables must have the same number of columns 2. Columns must be of the same data type 3. Columns order must be similar within the SELECT statement I will hereby explain these criterion using an example with data from the AdventureWorks database. 1. Tables must have the same number of columns To further explain, I will attempt performing a UNION on two tables which do not have the same number of columns.Here is the error that I arrived at. Now, I will select only one columns from each of these two tables and then perform the UNION. The output of this UNION is illustrated below. As you could see the UNION command has been successfully executed. 2. Columns must be the same data type In the previous SELECT statement both Columns in the UNION statement (i.e. Name and DocName) were of the same data type (i.e. Varchar). If otherwise, an error similar to the one in the illustration below will be returned. 3. Columns order must be similar This order is with respect to the data type. For example, say our first select contains two columns and the data types respectively are: Int and Varchar. In this case, the order of the columns in the second SELECT must also be Int followed by Varchar, otherwise an error will be returned. The screen shot below demonstrates this error. Only after placing columns in the same order (with respect to data type) in both SELECT statements will the UNION command return the desired aggregated outcome. See the screenshot below for a detailed. demonstration.
0 Comments
Leave a Reply. |
CategoriesArchives
June 2020
|