1、添加表
GO
IF NOT EXISTS(SELECT * FROM sys.tables WHERE name='table_name')
BEGIN
CREATE TABLE [dbo].[table_name]()
END
GO
2、添加列
1)IF NOT EXISTS(SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('table_name') AND name = 'column_name')
AND EXISTS(SELECT * FROM sys.tables WHERE object_id = OBJECT_ID('table_name'))
BEGIN
ALTER TABLE table_name ADD column_name column_type
END
2) GO
IF(NOT EXISTS(SELECT * FROM sys.columns s WHERE s.name = 'column_name' AND s.id = OBJECT_ID('table_name')))
ALTER TABLE table_name ADD column_name column_type
GO
3、删除列
GO
IF EXISTS(SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('table_name') AND name = 'column_name')
BEGIN
ALTER TABLE table_name DROP COLUMN column_name
END
GO
4、表字段改名
GO
IF EXISTS (SELECT 1 FROM sys.columns WHERE [object_id] = OBJECT_ID('table_name') AND [name] = 'old_column_name')
BEGIN
EXEC sys.sp_rename @objname = 'table_name.old_column_name' @newname = 'new_column_name' @objtype = 'COLUMN'
END
GO
5、创建视图
IF EXISTS ( SELECT *
FROM sys.views
WHERE object_id = OBJECT_ID(N'[dbo].[VIEW_NAME]'))
DROP VIEW [dbo].[VIEW_NAME]
GO
CREATE VIEW [dbo].[VIEW_NAME]
AS
SELECT A.xx,
B.xx,
C.xx
FROM TABLE_A A
LEFT JOIN TABLE_B B ON B.xx = A.xx
LEFT JOIN TABLE_C C ON C.xx = A.xx
WHERE a.xx = xx
GO
6、创建函数
GO
IF OBJECT_ID(N'FUNCTION_NAME') IS NOT NULL
DROP FUNCTION FUNCTION_NAME
GO
CREATE FUNCTION [dbo].[FUNCTION_NAME] (@parameterIn parametertype)
RETURNS Returntype --例如:RETURNS NVARCHAR(500)
AS
BEGIN
DECLARE @parameter parametertype
SET @parameter = (SELECT COLUMN FROM TABLE WHERE COLUMN = @parameterIn)
RETURN @parameter
END
GO
调用函数 SELECT [dbo].[FUNCTION_NAME] (parameterIn)
7、修改字段的类型
GO
IF EXISTS (SELECT 1 FROM sys.columns WHERE [object_id] = OBJECT_ID('table_name') AND [name] = 'column_name')
BEGIN
ALTER TABLE table_name ALTER COLUMN column_name type
END
GO