写sql语句创建视图的一个例子

值得注意的是本例使用了cast的方法将表中的id字段转化为nvarchar(255)类型再拼上我们想要的字母。

并且联合查询也可以保证从两个表中选取数据插入到视图。


IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
      WHERE TABLE_NAME = 'ViewProductReview')
   DROP VIEW [ViewProductReview]
GO   
CREATE VIEW [dbo].[ViewProductReview](
		[Id]
      ,[Body]
      ,[CreateDate]
      ,[LastUpdate]
      ,[StyleCustomId]
      ,[UserId]
      ,[UserName]
) AS select 'P-'+ cast ([Id] as nvarchar(255))
      ,[Body]
      ,[CreateDate]
      ,[LastUpdate]
      ,[StyleCustomId]
      ,[UserId]
      ,[UserName]
from ProductReview
union
select
    'A-'+cast([Id] AS nvarchar(255))
     ,[Body]
      ,[CreateDate]
      ,[LastUpdate]
      ,[StyleCustomId]
      ,[UserId]
      ,[UserName]
      FROM AdministratorReview
GO


你可能感兴趣的:(数据库)