Create view xxx
as
Select * from
DBName.dbo.table1
我有一个上面提到的DBName
是动态的视图。我该如何创建此视图?我知道我们不能在视图中使用动态变量。我想知道如何在函数的帮助下完成它。
答案 0 :(得分:0)
使用可以在这里使用同义词只需将DbName作为变量传递,如此
Declare @Dbname varchar(255)
Declare @qry varchar(255)
Set @Dbname="Name of the dataBase"
Set @qry='Create synonym ABC for'+@DbName+'.dbo.table1'
Exec (@qry)
现在使用此
IF EXISTS (SELECT 1 from sysobjects where id=object_id(''SN_DWTableCustomer'') and xtype=''SN'')
BEGIN
DROP VIEW xxx
Create view xxx as Select * from ABC
END
ELSE
BEGIN
Create view xxx as Select * from ABC
END
为了更好地理解,请使用以下链接 https://www.techonthenet.com/oracle/synonyms.php What is the use of SYNONYM in SQL Server 2008?
请回复。
答案 1 :(得分:0)
DECLARE @DBname varchar(max) = 'newdb'
DECLARE @sql varchar(max) = 'create view MyView as select * from '+@DBname+'.dbo.test'
EXEC (@sql)
SELECT * FROM MyView
答案 2 :(得分:0)
DECLARE @DB VARCHAR(100)
SET @DB = 'Your_DBName' DECLARE @CreateViewStatement NVARCHAR(MAX)
SET @CreateViewStatement = ' USE '+ QUOTENAME(@DB) +';
EXEC(''
CREATE VIEW [dbo].[MyTable] AS
SELECT * FROM Your_Table
'') '
EXEC (@CreateViewStatement)