Despite its undocumented status, master..spt_values is a valuable table that enables system procedures in Microsoft SQL Server to perform various functions effectively. It contains a collection of reference tables and projection data used by these system procedures, including lookup values for data types, roles, and other metadata.
Type = 'P' signifies the Projection table within master..spt_values. This table provides a consecutive sequence of numbers, from 0 to 2047, that can be used to perform projections or traversals through data.
The raw data stored in master..spt_values is not intended for direct use by user queries. However, its projection capabilities are particularly useful for splitting data within a single column.
Imagine a table where one column contains a comma-separated list of values, such as '1,2,3'. To transform this column into multiple rows, you can utilize spt_values as follows:
SELECT RIGHT(LEFT(T.col4,Number-1), CHARINDEX(',',REVERSE(LEFT(','+T.col4,Number-1)))) FROM master..spt_values, table1 T WHERE Type = 'P' AND Number BETWEEN 1 AND LEN(T.col4)+1 AND (SUBSTRING(T.col4,Number,1) = ',' -- OR SUBSTRING(T.col4,Number,1) = '') --this does not work correctly anyway
In this scenario, the query iterates through the spt_values table (Type = 'P') and uses the number sequence to guide the split operation. It effectively isolates each value within the comma-separated list, creating distinct rows in the result set.
Employing master..spt_values for column splitting offers several advantages:
The above is the detailed content of How Can master..spt_values Be Used for Efficient Column Splitting in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!