Created
August 7, 2020 19:21
-
-
Save jingyang-li/6ad6e4c6a0b6ba8a47da65c3d4fa0f23 to your computer and use it in GitHub Desktop.
Create View From All Tables In a DB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://stackoverflow.com/questions/23166423/how-to-create-view-for-all-tables-in-database | |
DECLARE @SQL nvarchar(MAX) | |
SET @SQL = N'' | |
SELECT | |
@SQL = @SQL + | |
N'IF EXISTS(SELECT 1 FROM sys.objects WHERE name = ''v_' + t.[TABLE_NAME] + ''' AND type = ''V'') BEGIN DROP VIEW [v_' + t.[TABLE_NAME] + '] END | |
EXEC(''CREATE VIEW [v_' + t.[TABLE_NAME] + N'] AS SELECT ' + | |
STUFF( | |
(SELECT distinct ',' + c.[COLUMN_NAME] | |
FROM [INFORMATION_SCHEMA].[COLUMNS] AS c | |
WHERE c.[TABLE_SCHEMA] =t.[TABLE_SCHEMA] and c.[TABLE_NAME]=t.[TABLE_NAME] | |
FOR XML PATH(''), TYPE).value('.','nvarchar(max)') | |
,1,1,'') | |
+ ' FROM [' + t.[TABLE_NAME] + '] '') | |
' | |
FROM [INFORMATION_SCHEMA].[TABLES] t | |
WHERE [TABLE_TYPE]='BASE TABLE' | |
EXEC sp_executesql @SQL | |
--print @SQL |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment