1. 程式人生 > 其它 >SQL Server 常用語句

SQL Server 常用語句

技術標籤:SQLsql資料庫

1,查詢所有的儲存過程(storedprocedure)的名字以及內容

SELECT
Name,--儲存過程名字
Definition --儲存過程內容
FROM sys.sql_modules AS m 
INNER JOIN sys.all_objects AS o ON m.object_id = o.object_id
WHERE o.[type] = 'P'

如果僅檢視名字的話,可以簡略一點:

select name from sysobjects where xtype='p'

2,查詢所有的檢視(view)的名字以及內容

SELECT
Name,--檢視名字
Definition --檢視內容
FROM sys.sql_modules AS m 
INNER JOIN sys.all_objects AS o ON m.object_id = o.object_id
WHERE o.[type] = 'v'

僅檢視名字的話,可以簡略如下:

Select name From sysobjects Where xtype='v'

3,統計DB的使用空間

exec sp_spaceused 'dbo.Member_Info'--統計單個表的使用空間
exec sp_MSforeachtable "exec sp_spaceused '?'"--統計每個表的使用空間

4,外來鍵的相關語句

SELECT * FROM sys.foreign_keys WHERE referenced_object_id = object_id('dbo.User_Info')--檢查/查詢關聯dbo.User_Info的外來鍵

alter table dbo.Survey_Detail drop constraint FK_Survey_Detail_S_ID --刪除外來鍵

ALTER TABLE [dbo].[Survey_Detail]--增加外來鍵
ADD CONSTRAINT [FK_Survey_Detail_S_ID] FOREIGN KEY (S_ID) references [dbo].[Survey] (S_ID)

alter table [dbo].[Member_Info] WITH NOCHECK --(不檢查表是否已存在資料,直接新增外來鍵約束)
add constraint FK_Member_Info_C_ID foreign key (C_ID) references [dbo].[Centre_Info](C_ID)

5,預設值的相關語句

--刪除表的預設值
sp_help User_Info;
ALTER TABLE User_Info DROP DF__User_Inf__U_Co__73852659; --由系統自動建立的預設值名字

ALTER TABLE [dbo].[Centre_Info] ADD [C_Code] [varchar] (15) NOT NULL DEFAULT '' --增加C_Code欄位並且設定預設值為空白字串

ALTER TABLE [dbo].[Device_Code] ADD CONSTRAINT DF_Device_Code_DC_Status DEFAULT 0 for [DC_Status] --- 將原有欄位設定預設值為0,並且指定了名字

6,欄位的相關語句

ALTER TABLE dbo.User_Info ADD [U_Password] [varchar] (50) NULL -- 增加欄位

ALTER TABLE dbo.Centre_Info ADD [C_Code] [varchar] (15) NOT NULL DEFAULT '' --增加C_Code欄位並且設定預設值

ALTER TABLE dbo.Member_Info DROP COLUMN M_Create_Centre_ID; --刪除M_Create_Centre_ID欄位

ALTER TABLE dbo.Log_Audit ALTER COLUMN [LA_RemoteIp] [varchar](30)  ------修改欄位型別

7,重新命名

--https://docs.microsoft.com/zh-cn/sql/relational-databases/tables/rename-columns-database-engine?view=sql-server-ver15
EXEC sp_rename 'dbo.Member_Info.M_In_Centre_ID', 'C_ID', 'COLUMN'; --重新命名列

8,刪除若干個儲存過程

declare @spList varchar(max),
	@spName varchar(100),
    @split varchar(10)

set @split = ','

set @spList = 'CheckIn_Info_Stat_SP';
set @spList += ',Device_Maintenance_SP';
set @spList += ',Recent_Week_Applicants_Stat_SP';
set @spList += ',Recent_Year_Applicants_Stat_SP'; --待刪除的儲存過程的名字列表

declare @dropSpSql nvarchar(300);
while(len(@spList)<>0)  
begin  
	if(charindex(@split,@spList)<>0) --名字列表中還含有分隔符
	begin
		set @spName = substring(@spList,1,charindex(@split,@spList)-1)   --取儲存過程名字
		set @spList = stuff(@spList,1,charindex(@split,@spList),'')      --修改名字列表
	end
	else
	begin
		set @spName = @spList;
		set @spList='';
	end

	if exists (select * from dbo.sysobjects where id = object_id(@spName) and OBJECTPROPERTY(id, N'IsProcedure') = 1) --判斷儲存過程是否存在
	begin
		set @dropSpSql = 'drop procedure ' + @spName; --刪除儲存過程的語句
		print @dropSpSql
		exec sp_executesql @dropSpSql    --執行SQL語句
		print 'Deleted SP: ' + @spName;
	end
	else 
	begin
		print 'SP: '[email protected]+' not exists!'
	end
end


print 'Drop Procedures End!';

9,刪除若干個表(Table)

刪除若干個表跟上面刪除若干個儲存過程的過程類似。但是如果表有外來鍵的話,則需要先刪除關聯的外來鍵。所以,難點在於,怎樣在迴圈中的不同的table之間找到外來鍵並且刪除它。

if object_id(N'tempdb..#foreignKeyTable',N'U') is not null --臨時表,整個DB包含的外來鍵等關係
begin
		drop table #foreignKeyTable
		print 'deleted #foreignKeyTable' 
end

if object_id(N'tempdb..#foreignKeyNameTable',N'U') is not null --臨時表,某個table包含的外來鍵的名字
begin
		drop table #foreignKeyNameTable
		print 'deleted #foreignKeyNameTable' 
end

select
a.name as ConstraintName,
object_name(b.parent_object_id) as ForeignKeyTable, 
d.name as ForeignKey,
object_name(b.referenced_object_id) as MainTable,
c.name as MainKey
into #foreignKeyTable
from sys.foreign_keys A
inner join sys.foreign_key_columns B on A.object_id=b.constraint_object_id
inner join sys.columns C on B.parent_object_id=C.object_id and B.parent_column_id=C.column_id 
inner join sys.columns D on B.referenced_object_id=d.object_id and B.referenced_column_id=D.column_id 

print '--------------------------------搜尋外來鍵,完畢-----------------------------------';

declare @tableList varchar(max),
    @tableName varchar(100),
    @split varchar(10)
    
set @split = ','

set @tableList = 'Device_Centre_Link';
set @tableList += ',Device_Code_Apply';
set @tableList += ',Device_Code_Maintenance'; --有Foreign key的Table
set @tableList += ',Device_DataSchema_Collection'; --有Foreign key的Table

declare @constraintName varchar(100);
declare @foreignKeyTable varchar(100);
declare @dropForeignKeySql nvarchar(max);
declare @dropTableSql nvarchar(300);

while(len(@tableList)<>0)  
begin  

	if(charindex(@split,@tableList)<>0)
	begin
		set @tableName = substring(@tableList,1,charindex(@split,@tableList)-1)  
		set @tableList = stuff(@tableList,1,charindex(@split,@tableList),'')  
	end
	else
	begin
		set @tableName = @tableList;
		set @tableList='';
	end

	if OBJECT_ID(@tableName,N'U') is not null
    begin
		print 'Table: '[email protected]+' exists!'
		SELECT name into #foreignKeyNameTable FROM sys.foreign_keys WHERE referenced_object_id = object_id(@tableName) --檢查/查詢Table關聯的外來鍵
		
		while exists(select name from #foreignKeyNameTable)
		begin
			select top 1 @constraintName = name from #foreignKeyNameTable;
			select top 1 @foreignKeyTable = ForeignKeyTable from #foreignKeyTable where ConstraintName = @constraintName;

			set @dropForeignKeySql='alter table [dbo].['[email protected]+'] drop constraint '[email protected]+''--刪除外來鍵
			print @dropForeignKeySql
			exec sp_executesql @dropForeignKeySql

			delete from #foreignKeyNameTable where name = @constraintName;
		end

		set @dropTableSql = 'drop table ' + @tableName;
		print @dropTableSql
		exec sp_executesql @dropTableSql

		drop table #foreignKeyNameTable;
	end
	else 
	begin
		print 'Table: '[email protected]+' not exists!'
	end
end  

drop table #foreignKeyTable;

print 'Drop Tables End!';

print '-----------------------------------------------------------------------------';