1. Select 語句中含有參數,可以使用exec( )語句執行。
2. 可以用下列方法得到字符串'1234':
Declare @str Varchar(10)
Set @str = '1234'
Print @str ---此時結果:1234
Set @str = '''1234'''
Print @str ---此時結果:'1234'
3. 可以用下列語句修改資料表欄位:
ALTER TABLE GPDB.dbo.Branch ALTER COLUMN BranchID VARCHAR(19) NOT NULL
4. 例如:
/*********************************************************
**CreateDate:2007/06/26
**CreateUser:yangyongli
**功能描述 :修改資料庫中所有欄位
** BranchID,OLD_BranchID --> varchar(19)
**********************************************************/
Create Table #temp(dbName Varchar(128), --資料庫名稱
dbID int, --資料庫id
xtype Char(2)) --類別 xtype = U:用戶自定義
Create Table #tempCol(colID int, --資料列ID (欄位id)
colName Varchar(128)) --資料列名稱(欄位名稱)
Declare @strdbName Varchar(20) ---資料庫DataBase名稱
Declare @strtbName Varchar(30) ---資料表table名稱
Declare @strExec Varchar(255) ---執行語句串
--取得所有用戶定義的資料庫DataBase名稱
Declare cur_dbName Cursor For
Select Name
From Master.dbo.sysdatabases
Where 1 = 1
And Name <> 'master'
And Name <> 'tempdb'
And Name <> 'model'
And Name <> 'msdb'
And Name <> 'pubs'
And Name <> 'Northwind'
And Name <> 'ReportServer'
And Name <> 'ReportServerTempDB'
--打開DataBase層遊標
OPEN cur_dbName
While 1 = 1
Begin
FETCH NEXT FROM cur_dbName Into
@strdbName
IF NOT (@@FETCH_STATUS = 0)
Break
Set @strExec = 'Select name dbName, id dbID, xtype From ' + @strdbName + '.dbo.sysObjects Where 1 = 1 And status > 0'
--Print @strExec
exec('Insert Into #temp ' + @strExec)
--取得所有用戶定義的table名稱
Declare cur_tbName Cursor For
Select dbName
From #temp
Where 1 = 1
And xtype = 'U'
--打開table層遊標
OPEN cur_tbName
While 1 = 1
Begin
FETCH NEXT FROM cur_tbName Into
@strtbName
IF NOT (@@FETCH_STATUS = 0)
Break
--Print @strtbName
Set @strExec = 'Select id ColID, name colName From ' + @strdbName + '.dbo.sysColumns Where ID = (Select ID From ' + @strdbName + '.dbo.sysObjects Where Name = ''' + @strtbName + ''') And (Name = ''BranchID'' Or Name = ''OLD_BranchID'')'
Print @strExec
exec('Insert Into #tempCol ' + @strExec)
/*If Exists(Select * From #tempCol Where 1 = 1)
Begin
Select @strtbName tbName, * From #tempCol
End*/
--若存在BranchID欄位,則修改
If Exists(Select *
From #tempCol
Where 1 = 1 And colName = 'BranchID')
BEGIN
--修改BranchID欄位:Varchar(6) --> Varchar(19)
Set @strExec = 'ALTER TABLE ' + @strdbName + '.dbo.' + @strtbName + ' ALTER COLUMN BranchID VARCHAR(19) NOT NULL'
print @strExec
--Exec(@strExec)
END
--若存在OLD_BranchID欄位,則修改
If Exists(Select *
From #tempCol
Where 1 = 1 And colName = 'OLD_BranchID')
BEGIN
--修改OLD_BranchID欄位:Varchar(6) --> Varchar(19)
Set @strExec = 'ALTER TABLE ' + @strdbName + '.dbo.' + @strtbName + ' ALTER COLUMN OLD_BranchID VARCHAR(19) NOT NULL'
print @strExec
--Exec(@strExec)
END
--刪除臨時表#tempCol中的資料
Delete From #tempCol
End
CLOSE cur_tbName
DEALLOCATE cur_tbName
--刪除臨時表#temp中的資料
Delete From #temp
End
CLOSE cur_dbName
DEALLOCATE cur_dbName
--刪除臨時表
Drop Table #temp
Drop Table #tempCol