SQL 은 라 이브 러 리 구축 표 에서 전체 튜 토리 얼 을 향상 시 킵 니 다.

 、  
1、  :     
CREATE DATABASE database-name 
2、  :     
drop database dbname
3、  :  sql server
---          device
USE master
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat'
---      
BACKUP DATABASE pubs TO testBack 
4、  :    
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)
          : 
A:create table tab_new like tab_old (        )
B:create table tab_new as select col1,col2… from tab_old definition only
5、  :    
drop table tabname 
6、  :     
Alter table tabname add column col type
 :         。DB2              ,         varchar     。
7、  :    : Alter table tabname add primary key(col) 
  :    : Alter table tabname drop primary key(col) 
8、  :    :create [unique] index idxname on tabname(col….) 
    :drop index idxname
 :        ,          。
9、  :    :create view viewname as select statement 
    :drop view viewname
10、  :        sql  
  :select * from table1 where   
  :insert into table1(field1,field2) values(value1,value2)
  :delete from table1 where   
  :update table1 set field1=value1 where   
  :select * from table1 where field1 like ’%value1%’ ---like      ,   !
  :select * from table1 order by field1,field2 [desc]
  :select count as totalcount from table1
  :select sum(field1) as sumvalue from table1
  :select avg(field1) as avgvalue from table1
  :select max(field1) as maxvalue from table1
  :select min(field1) as minvalue from table1
11、  :         
A: UNION     
UNION               (   TABLE1   TABLE2)                   。  ALL   UNION      (  UNION ALL),      。     ,            TABLE1      TABLE2。 
B: EXCEPT     
EXCEPT            TABLE1      TABLE2                     。  ALL   EXCEPT       (EXCEPT ALL),      。 
C: INTERSECT    
INTERSECT          TABLE1   TABLE2                       。  ALL   INTERSECT       (INTERSECT ALL),      。 
 :                   。 
12、  :      
A、left (outer) join: 
    (   ):             ,           。 
SQL: select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c
B:right (outer) join: 
    (   ):               ,           。 
C:full/cross (outer) join: 
    :             ,              。
12、  :Group by:
      ,        ,             。
          :(    ) count,sum,max,min,avg       )
     SQLServer    :   text,ntext,image           
    selecte        ,            ;
13、        :
        : sp_detach_db;      :sp_attach_db     ,          
14.          :
sp_renamedb 'old_name', 'new_name' 
 、  
1、  :   (     ,   :a    :b) (Access  )
  :select * into b from a where 1<>1(   SQlServer)
  :select top 0 * into b from a
2、  :   (    ,   :a     :b) (Access  )
insert into b(a, b, c) select d,e,f from b;
3、  :          (          ) (Access  )
insert into b(a, b, c) select d,e,f from b in ‘     ’ where   
  :..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where..
4、  :   (  1:a   2:b)
select a,b,c from a where a IN (select d from b )   : select a,b,c from a where a IN (1,2,3)
5、  :    、          
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b
6、  :     (  1:a   2:b)
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c
7、  :      (  1:a )
select * from (SELECT a,b,c FROM a) T where t.a > 1;
8、  :between   ,between               ,not between   
select * from table1 where time between time1 and time2
select a,b,c, from table1 where a not between   1 and   2
9、  :in      
select * from table1 where a [not] in (‘ 1’,’ 2’,’ 4’,’ 6’)
10、  :     ,                 
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )
11、  :      :
select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....
12、  :            
SQL: select * from      where datediff('minute',f    ,getdate())>5
13、  :  sql          
select top 10 b.* from (select top 20     ,     from    order by      desc) a,   b where b.     = a.     order by a.    
    :
       :
  declare @start int,@end int 
  @sql  nvarchar(600)
  set @sql=’select top’+str(@end-@start+1)+’+from T where rid not in(select top’+str(@str-1)+’Rid from T where Rid>-1)’
  exec sp_executesql @sql
--  : top          ,                    。Rid      ,  top    ---    ,          。         top           ,              ( --                   ,                 )
14、  : 10   
select top 10 * form table1 where   

--5、  :      b          a          (                  ,        ,       ,  .)
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)



16、  :      TableA      TableB TableC                     
(select a from tableA ) except (select a from tableB) except (select a from tableC)


17、  :    10   
select top 10 * from tablename order by newid()


18、  :      
select newid()


19、  :      

1),delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)

2),select distinct * into temp from tablename
  delete from tablename
  insert into tablename select * from temp
  :               ,               

3),  :           ,                ,         ,            ,             ,        
alter table tablename


--       
add  column_b int identity(1,1)
 delete from tablename where column_b not in(
select max(column_b)  from tablename group by column1,column2,...)
alter table tablename drop column column_b


20、  :           
select name from sysobjects where type='U' // U    


21、  :          
select name from syscolumns where id=object_id('TableName')

22、  :  type、vender、pcs  , type    ,case           ,  select   case。
select type,sum(case vender when 'A' then pcs else 0 end),sum(case vender when 'C' then pcs else 0 end),sum(case vender when 'B' then pcs else 0 end) FROM tablename group by type
    :
type vender pcs
   A 1
   A 1
   B 2
   A 2
   B 3
   C 3


23、  :    table1
TRUNCATE TABLE table1


24、  :   10 15   
select top 5 * from (select top 15 * from table order by id asc) table_   order by id desc


 、  
1、1=1,1=2   , SQL         
“where 1=1”            “where 1=2”    ,
 :
if @strWhere !='' 
begin
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere 
end
else 
begin
set @strSQL = 'select count(*) as Total from [' + @tblName + ']' 
end 
        
  !      。
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1    '+ @strWhere 2、     
--    
DBCC REINDEX
DBCC INDEXDEFRAG
--       
DBCC SHRINKDB
DBCC SHRINKFILE



3、     
dbcc shrinkdatabase(dbname)



4、                 
exec sp_change_users_login 'update_one','newname','oldname'
go


5、     
RESTORE VERIFYONLY from disk='E:\dvbbs.bak'


6、     
ALTER DATABASE [dvbbs] SET SINGLE_USER
GO
DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK
GO
ALTER DATABASE [dvbbs] SET MULTI_USER
GO


7、    
SET NOCOUNT ON
DECLARE @LogicalFileName sysname,
 @MaxMinutes INT,
 @NewSize INT


USE tablename --         
SELECT  @LogicalFileName = 'tablename_log', --      
@MaxMinutes = 10, -- Limit on time allowed to wrap log.
 @NewSize = 1  --             (M)

Setup / initialize
DECLARE @OriginalSize int
SELECT @OriginalSize = size 
 FROM sysfiles
 WHERE name = @LogicalFileName
SELECT 'Original Size of ' + db_name() + ' LOG is ' + 
 CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' + 
 CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB'
 FROM sysfiles
 WHERE name = @LogicalFileName
CREATE TABLE DummyTrans
 (DummyColumn char (8000) not null)


DECLARE @Counter    INT,
 @StartTime DATETIME,
 @TruncLog   VARCHAR(255)
SELECT @StartTime = GETDATE(),
 @TruncLog = 'BACKUP LOG ' + db_name() + ' WITH TRUNCATE_ONLY'

DBCC SHRINKFILE (@LogicalFileName, @NewSize)
EXEC (@TruncLog)
-- Wrap the log if necessary.
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired
 AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName)  
 AND (@OriginalSize * 8 /1024) > @NewSize  
 BEGIN -- Outer loop.
SELECT @Counter = 0
 WHILE   ((@Counter < @OriginalSize / 16) AND (@Counter < 50000))
 BEGIN -- update
 INSERT DummyTrans VALUES ('Fill Log') DELETE DummyTrans
 SELECT @Counter = @Counter + 1
 END
 EXEC (@TruncLog)  
 END
SELECT 'Final Size of ' + db_name() + ' LOG is ' +
 CONVERT(VARCHAR(30),size) + ' 8K pages or ' + 
 CONVERT(VARCHAR(30),(size*8/1024)) + 'MB'
 FROM sysfiles 
 WHERE name = @LogicalFileName
DROP TABLE DummyTrans
SET NOCOUNT OFF 


8、  :     
exec sp_changeobjectowner 'tablename','dbo'


9、       
CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch
@OldOwner as NVARCHAR(128),
@NewOwner as NVARCHAR(128)
AS

DECLARE @Name    as NVARCHAR(128)
DECLARE @Owner   as NVARCHAR(128)
DECLARE @OwnerName   as NVARCHAR(128)

DECLARE curObject CURSOR FOR 
select 'Name'    = name,
   'Owner'    = user_name(uid)
from sysobjects
where user_name(uid)=@OldOwner
order by name

OPEN   curObject
FETCH NEXT FROM curObject INTO @Name, @Owner
WHILE(@@FETCH_STATUS=0)
BEGIN     
if @Owner=@OldOwner 
begin
   set @OwnerName = @OldOwner + '.' + rtrim(@Name)
   exec sp_changeobjectowner @OwnerName, @NewOwner
end
-- select @name,@NewOwner,@OldOwner

FETCH NEXT FROM curObject INTO @Name, @Owner
END

close curObject
deallocate curObject
GO


10、SQL SERVER         
declare @i int
set @i=1
while @i<30
begin
    insert into test (userid) values(@i)
    set @i=@i+1
end
  :
    ,              ,     0.1    ,       :
    Name     score
    Zhangshan   80
    Lishi       59
    Wangwu      50
    Songquan    69
while((select min(score) from tb_table)<60)
begin
update tb_table set score =score*1.01 
where score<60
if  (select min(score) from tb_table)>60
  break
 else
    continue
end

    -  



1.       :
Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as //    


2.     :
select encrypt('    ')
select pwdencrypt('    ')
select pwdcompare('    ','     ') = 1--  ;      encrypt('    ')
select pwdencrypt('    ')
select pwdcompare('    ','     ') = 1--  ;     


3.      :
declare @list varchar(1000),
@sql nvarchar(1000) 
select @list=@list+','+b.name from sysobjects a,syscolumns b where a.id=b.id and a.name=' A'
set @sql='select '+right(@list,len(@list)-1)+' from  A' 
exec (@sql)


4.      :
EXEC master..xp_fixeddrives


5.  A,B     :
if (select checksum_agg(binary_checksum(*)) from A)
     =
    (select checksum_agg(binary_checksum(*)) from B)
print '  '
else
print '   '


6.            :
DECLARE hcforeach CURSOR GLOBAL FOR SELECT 'kill '+RTRIM(spid) FROM master.dbo.sysprocesses
WHERE program_name IN('SQL profiler',N'SQL      ')
EXEC sp_msforeach_worker '?'


7.    :
   N   
Select Top N * From  
-------------------------------
N M   (     ID)
Select Top M-N * From   Where ID in (Select Top M ID From  ) Order by ID   Desc
----------------------------------
N     
Select Top N * From   Order by ID Desc
  
  1:          ,        RecID       ,    SQL  ,      31  40   。
 select top 10 recid from A where recid not  in(select top 30 recid from A)
  :            ,  recid         。
    select top 10 recid from A where……       ,    select top 30 recid from A        ,                      ,                    。
    


1,  order by select top 30 recid from A order by ricid           ,      


2,            :select top 30 recid from A where recid>-1
 2:           ,             ,     。
set @s = 'select top 1 * from T   where pid not in (select top ' + str(@count-1) + ' pid  from  T)'
print @s      exec  sp_executesql  @s


9:              
select Name from sysobjects where xtype='u' and status>=0


10:           
select name from syscolumns where id=object_id('  ')
select name from syscolumns where id in (select id from sysobjects where type = 'u' and name = '  ')
         


11:            、    、  
select a.* from sysobjects a, syscomments b where a.id = b.id and b.text like '%  %'


12:              
select name as        from sysobjects where xtype='P'


13:            
select * from master..sysdatabases D where sid not in(select sid from master..syslogins where name='sa')
  
select dbid, name AS DB_NAME from master..sysdatabases where sid <> 0x01


14:              
select column_name,data_type from information_schema.columns
where table_name = '  ' 


15:               
--        
exec sp_addlinkedserver   'ITSV ', ' ', 'SQLOLEDB ', '       ip   ' 
exec sp_addlinkedsrvlogin  'ITSV ', 'false ',null, '    ', '   ' 
--     
select * from ITSV.    .dbo.   
--     
select * into   from ITSV.    .dbo.   
--               
exec sp_dropserver  'ITSV ', 'droplogins ' 
 
--    /     (openrowset/openquery/opendatasource) 


--1、openrowset 
--     
select * from openrowset( 'SQLOLEDB ', 'sql     '; '    '; '   ',    .dbo.  ) 
--      
select * into   from openrowset( 'SQLOLEDB ', 'sql     '; '    '; '   ',    .dbo.  ) 
 
--          
insert openrowset( 'SQLOLEDB ', 'sql     '; '    '; '   ',    .dbo.  ) 
select *from     
--      
update b 
set b. A=a. A 
 from openrowset( 'SQLOLEDB ', 'sql     '; '    '; '   ',    .dbo.  )as a inner join     b 
on a.column1=b.column1 
--openquery           
--                
exec sp_addlinkedserver   'ITSV ', ' ', 'SQLOLEDB ', '       ip   ' 
--   
select * 
FROM openquery(ITSV,  'SELECT *  FROM    .dbo.   ') 
--          
insert openquery(ITSV,  'SELECT *  FROM    .dbo.   ') 
select * from     
--      
update b 
set b. B=a. B 
FROM openquery(ITSV,  'SELECT * FROM    .dbo.   ') as a  
inner join     b on a. A=b. A 
 

--3、opendatasource/openrowset 
SELECT   * 
FROM   opendatasource( 'SQLOLEDB ',  'Data Source=ip/ServerName;User ID=   ;Password=   ' ).test.dbo.roy_ta 
--          
insert opendatasource( 'SQLOLEDB ',  'Data Source=ip/ServerName;User ID=   ;Password=   ').   .dbo.   
select * from      
SQL Server    
SQL Server    

1.             


1,datalength(Char_expr)           ,         


2,substring(expression,start,length)    ,        “1”,start     ,length      ,      len(expression)     


3,right(char_expr,int_expr)         int_expr   ,  left    


4,isnull( check_expression , replacement_value )  check_expression  ,   replacement_value  ,   ,   check_expression      


5,Sp_addtype        
  :EXEC sp_addtype birthday, datetime, 'NULL'


6,set nocount {on|off}              Transact-SQL           。                         ,               ,         。SET NOCOUNT             ,         。SET NOCOUNT   ON  ,     (    Transact-SQL        )。

SET NOCOUNT   OFF  ,        SQL   :from             :256 SQL      Order by,   ,   ,   SQL ,          8000,   nvarchar(4000),  nvarchar Unicode 。          
SQLServer2000           、     

1.     ,             windows  ,        ,                --    --     --    --    --    --       administrator    windows   (SynUser)

2.       ,        ,              ,  :    --D:\       ,  : PUB--         --  --  --  "      "--  "  "            ,           (SynUser)              --  

3.  SQL  (SQLSERVERAGENT)       (  /          )  --  --    --  --  SQLSERVERAGENT--  --  --  "   "--             windows     (SynUser)--"  "         

4.  SQL Server      ,          (  /          )     --  SQL  --  --   --    --  "SQL Server   Windows"--  

5.                      --  SQL Server --  SQL Server  ...--   --       ,              --  --   --    ,     "SQL Server    "--   --        (SynUser)--   --  SQL Server ,         --   --  

6.     IP,        ,         (         ) (      ,  ,           ,                IP)  --  --Microsoft SQL Server--         --  --  --     "tcp/ip"--       SQL    --    --        SQL   ip  --      SQL   ,    "      ",         





 、     

1、              ,      (B、C、D)       :
    (1)  [  ]     [  ]      [    、        ]            
    (2) [   ]                                sql    (    )
    (3) [   ]            \\servername\Pub
    (4) [   ]           : ,                          ,        (  )
    (5) [   ]                   
    (6) [   ]                   
    (7) [   ]                
    (8) [   ]          
    (9) [   ]     
2、          B、C、D 
    (1) [  ]   [  ]      [       ]  
    (2)            ,    [    ]
    (3) [      ]         [   ]           。               。                  (             )
    (4)  [   ]                      ,SQLSERVER           orACLE ACCESS        。           "SQL SERVER 2000"       
    (5)  [   ]                           :                             
    (6)         
    (7)               :           ,                            (          )
    (8)[   ]           
    (9)[   ]             1)        ,                   : [  ]->[  ]->[    、           ]->[     ]                        :                             [     ]->[  ]->[    ]->[  ]->[    ]           2)        ,                 
    (10)[   ]            
    (11)[   ]     
                                  
srv1.  ..author   :id,name,phone, srv2.  ..author   :id,name,telphone,adress  
  : srv1.  ..author     srv1.  ..author     srv1.  ..author phone    , srv1.  ..author    telphone   --*/  --        --1.  srv1         ,    srv1     srv2,     exec sp_addlinkedserver 'srv2','','SQLOLEDB','srv2 sql    ip' exec sp_addlinkedsrvlogin 'srv2','false',null,'   ','  ' go--2.  srv1   srv2       ,   msdtc(         ),         。    --    --    --  --   Distributed Transaction Coordinator--  --  --              go   --                                  --   --SQL Server   --     --     --"  "         --"  "  --   --"   "       --"  "   "Transact-SQL   (TSQL)" --"   "           --"  "         : exec p_process --   --"  "  --     --"  "        --"    "            --    "    " -- "  "               SQL Agent    ,        ,                 :     --    --    --  --   SQLSERVERAGENT--  --    --  "    "--  .   --3.         2,      -- srv1               create proc p_process as --         update b set name=i.name,telphone=i.telphone from srv2.  .dbo.author b,author i where b.id=i.id and(b.name <> i.name or b.telphone <> i.telphone)  --        insert srv2.  .dbo.author(id,name,telphone) select id,name,telphone from author i where not exists( select * from srv2.  .dbo.author where id=i.id)  --         (      ) delete b from srv2.  .dbo.author b where not exists( select * from author where id=b.id)go

좋은 웹페이지 즐겨찾기