1. 程式人生 > 實用技巧 >Sqlserver 常用 SQL

Sqlserver 常用 SQL


1.Batch update top 10

2.Backup table

3.Add/Alter column and PK

4.Create/Replace Index

5.Dynamic Create/Replace sequence

6.Create/Replace Stored Procedure

7.Create/Replace function



1
.Batch update top 10 update top(10) tablename set id=1 where id is null 2.Backup table select * into new_table from old_table
3.Add/Alter column and PK ALTER TABLE table_name DROP CONSTRAINT pk_name ALTER TABLE table_name ALTER COLUMN name_no char(2) not null ALTER TABLE table_name ADD country char(10) not null ALTER TABLE table_name ADD CONSTRAINT pk_name PRIMARY KEY CLUSTERED (id, name) 4.Create/Replace Index IF EXISTS (
SELECT * FROM sys.objects so JOIN sys.indexes si ON so.object_id = si.object_id JOIN sys.schemas sc ON so.schema_id = sc.schema_id WHERE so.name = N'table_name' AND sc.name = N'schema' AND si.name = N'index_name' AND so.type in (N'U')) DROP INDEX [index_name] ON [schema
].[table_name] GO CREATE NONCLUSTERED INDEX [index_name] ON [schema].[table_name] ( [id] ASC, [name] ASC ) WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY] GO 5.Dynamic Create/Replace sequence IF EXISTS(SELECT * FROM sys.sequences WHERE name = N'sequence_name') DROP SEQUENCE schema.sequence_name; DECLARE @start_value varchar(20),@create_seq_sql nvarchar(2000) SELECT @start_value = max(id) FROM shema.table_name WHERE id IS NOT NULL IF @start_value IS NULL SET @start_value=0 SELECT @create_seq_sql = ' CREATE SEQUENCE schema.sequence_name AS bigint START WITH ' + @start_value + ' INCREMENT BY 1' EXEC sp_executesql @create_seq_sql GO 6.Create/Replace Stored Procedure IF EXISTS (select * from dbo.sysobjects where id = object_id(N'[schema].[sp_name]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [schema].[sp_name] GO CREATE PROCEDURE [schema].[sp_name] @param_1 numeric(20, 0), @param_2 varchar(10) AS BEGIN -- business logic END GO 7.Create/Replace function IF EXISTS(SELECT * FROM sys.sysobjects WHERE id = object_id(N'schema.function_name') and xtype='FN') DROP FUNCTION [schema].[function_name] GO CREATE function [schema].[function_name]( @param NVARCHAR(1000) ) returns NVARCHAR(1000) as begin -- bisiness logic return '' end go