search
HomeDatabaseMysql TutorialSQLServer中常用的一些操作表,字段和索引的SQL语句

我 常用 的 一些 SQLServer中 操作 表,字段和 索引 的SQL 语句 ,Post到这里,留作备忘录。 LastUpdate: 2012-12-31 -- 创建表,带主键CREATE TABLE 新表名( [fID] [int] IDENTITY(1,1) NOT NULL, [fa] [int] NULL, [fb] [smallint] NULL, [fc] [tinyint] N

常用一些SQLServer中操作表,字段和索引的SQL语句,Post到这里,留作备忘录。

LastUpdate: 2012-12-31

-- 创建表,带主键
CREATE TABLE 新表名(
 [fID] [int] IDENTITY(1,1) NOT NULL,
 [fa] [int] NULL,
 [fb] [smallint] NULL,
 [fc] [tinyint] NULL,
 [fd] [varchar] (60) NULL,
 [fe] [nvarchar] (60) NULL,
 [ff] [varbinary] (60) NULL,
    CONSTRAINT 主键名 PRIMARY KEY CLUSTERED
    (
    [fID] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,
     ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]

-- 删除表
drop table 表名

-- 字段改名
exec sp_rename '表名.旧字段名', '新字段名', 'Column'

-- 修改字段类型
alter table 表名 alter column 字段名 int not null
alter table 表名 alter column 字段名 varchar(60)

-- 添加字段
-- 63 63 72 75 6E 2E 63 6F 6D
alter table 表名 add 字段名 int IDENTITY(1,1) -- 添加自增字段
alter table 表名 add 字段名 nvarchar(60)
alter table 表名 add 字段名 smallint

-- 删除字段
alter table 表名 drop column 字段名

-- 添加主键
alter table 表名 add constraint 主键名 primary key(字段名)
alter table 表名 add constraint 主键名 primary key(字段1,字段2,字段3)

-- 设置主键不能为空
alter table 表名 alter column 主键名 not null

-- 删除主键
alter table 表名 drop 主键名

-- 创建<strong>索引</strong>
create index <strong>索引</strong>名 on 表名(字段名)
create index <strong>索引</strong>名 on 表名(字段1,字段2,字段3)

-- 删除<strong>索引</strong>
drop index <strong>索引</strong>名 on 表名

-- 随机筛选记录
select 字段1,字段2 from 表名 where 条件 order by newid()

-- 查看SQLServer中各表占用大小情况
exec sp_MSforeachtable "exec sp_spaceused '?'"

-- 重建<strong>索引</strong>
dbcc dbreindex('表名')
dbcc dbreindex('表名', '<strong>索引</strong>名')
dbcc dbreindex('表名', '<strong>索引</strong>名', 90)

-- 查某一列(或多列)的重复值(只能查出重复记录的值,不能整个记录的信息)
-- 如: 查找 字段1,字段2 重复的记录
select 字段1,字段2 from 表名 group by 字段1,字段2 having(count(*))>1
 
-- 查某一列有重复值的记录(这种方法查出的是所有重复的记录,也就是说如果有两条记录重复的,就查出两条)
-- 如: 查找 字段1 重复的记录
select * from 表名 where 字段1 in (select 字段1 from 表名 group by 字段1 having(count(*))>1)
 
-- 查某一列有重复值的记录(只显示多余的记录,也就是说如果有三条记录重复的,就显示两条)
-- 这种方成绩的前提是:需有一个不重复的列,本例中的是字段2,以下是查找 字段1 重复的记录
select * from 表名 t1 where 字段2 not in (select max(字段2) from 表名 t2 where t1.字段1=t2.字段1)

-- 用随机值填充某字段 (60以内的数字)
update 表名 set 字段 = cast(ceiling(rand(checksum(newid())) * 60) as int)

-- 增加约束
alter table 表名 add constraint [DF_表名_字段名] default ('默认值') FOR [字段名] -- ((0))

-- 删除约束
alter table 表名 drop constraint 约束名 

-- 查询约束名
select c.name from sysconstraints a 
inner join syscolumns b on a.colid=b.colid 
inner join sysobjects c on a.constid=c.id 
where a.id=object_id('表名') and b.name='字段名'
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),