sqlserver简单操作手册
MSSQLSERVER2008数据库使用手册

MS SQLSERVER 2008数据库使用手册
一、导入数据库架构
1、打开本地计算机上的SQL Server Management Studio 客户端软件:
2、登陆本机数据库控制端:
3、选择生成SQL脚本:
4、选中需要导出脚本的库名:
5、选择兼容sql2005的版本的脚本:
6、修改sql脚本的保存路径:
7、查看生产脚本生成的选项:
8、成功生成sql脚本:
9、等待脚本生成完毕,进入存放目录用记事本打开脚本文件,修改库名为万网提供的数据库名,并
确保您的脚本中所有者是DBO,否则请替换成DBO:
10、连接到万网提供的目标数据库服务器:
注:IP一项也可以填入数据库服务器的域名:us*-**(us******)
11、并点击新建查询,拷贝您记事本中的SQL 脚本代码到上图显示的查询分析器中,点击分析脚本,如果没有语法错误,就点击执行脚本,直到执行完毕。
到此,您的数据库架构已经完整的导入到万网的数据库服务器。
二、下面咱们开始导入数据库表中的数据:
1、登陆您本地的数据库:
2、点击您本地计算机上的数据库右键-任务-导出数据:
3、选择目标数据库,如下添加万网提供给您的数据库信息(服务器地址,用户名,密码,数据库):
4、点击下一步:
5、点击下一步,选中所有表,并确保“目标”中是DBO 的所有者:
6、点击下一步:
7、点击下一步,直到执行完毕:
8、成功导入数据:
到此,您的库已经完整的导入到万网提供的数据库服务器中,您可以用程序进行调用读取了。
SQL server使用教程

∙1、怎么登录SQLServer?∙2、怎么导入数据库结构?∙3、怎么导入导出数据?操作说明:SQL数据库备份/还原,都是数据导入导出数据的过程。
备份的时候,源数据库是服务器上的数据库(您的网站所使用的数据库),目标数据库是本地数据库。
恢复的时候,源数据库是是本地数据库,目标数据库服务器上的数据库(您的网站所使用的数据库)。
1、怎么登录SQLServer?1、安装好SQL2008后,在开始菜单中找到SQL Server Management Studio,并点击打开。
2、数据数据库信息,点击连接。
3、如果信息正确,就可以登录数据库了进行操作了。
TOP2、怎么导入数据库结构?1、连接上SQL Server怎么登录SQLServer?,在左侧找到要操作的数据库,点击任务/生成脚本。
2、进入欢迎页面,点击下一步。
3、选择要操作的数据库,点击下一步。
4、在选项中找到【为服务器版本编写脚本】,选择目标数据库的版本,一般为SQL 2008,然后点击下一步。
5、选择要编写脚本的对象,[?]不建议选择表。
如果包换存储过程,用户自定义的函数,视图,则将其选中。
然后点击下一步。
如果选项中只有表,恭喜您,无需进行导入数据库结构操作,直接导入数据就可以了。
6、本步骤会列出第5步选中的项目,选择全选,然后下一步。
7、选择脚本存放位置,其他选项默认即可,然后点击完成,即可生成脚本。
8、重新连接到要导入数据的数据库怎么登录SQLServer?,在要操作的数据库上点击新建查询。
9、打开刚才导出的脚本,并点击执行,即可导入数据库结构。
TOP3、怎么导入导出数据?1、连接上SQL Server怎么登录SQLServer?,在左侧找到要操作的数据库,点击任务/导出数据(点击导入数据,效果一样)。
2、进入欢迎页面,点击下一步。
3、填入数据源信息,点击下一步。
4、填入要导入的目标数据库信息,点击下一步。
5、选择【复制一个或多个标或视图的数据】,点击下一步。
【免费下载】SQLSERVER使用手册

Microsoft SQL SERVER 2000使用手册在网络环境下进行数据库系统的应用开发,需要选择具体的DBMS。
本章首先介绍当前流行的关系数据库系统Microsoft SQL Server的基本知识,接着以Microsoft SQL Server 2000为背景,介绍数据库系统设计的方法和SQL Server的高级应用技术。
1 SQL Server简介Microsoft SQL Server是高性能、客户/服务器的关系型数据库管理系统RDBMS,能够支持大吞吐量的事务处理,也能在Microsoft Windows 2000 Server网络环境下管理数据的存取以及开发决策支持应用程序。
由于Micriosoft SQL Server是开放式的系统,其他系统可以与它进行完好的交互操作。
1.1 SQL Server 2000的特点(1)对操作系统的要求低SQL Server 2000除了继续支持Windows 2000 Server外,还新增了SQL Server 2000桌面版(Desktop Edition),此版本可以安装在Windows 95/98/2000专业版上,用来建立数据库,这使得SQL Server 2000变得非常通用,可以在任何大小的计算机上运行,包括膝上机、台式机和高档服务器。
(2)管理自动化许多关键性的工作、数据库调整和最佳化处理等都由系统自动完成,减少了人为手工调整。
例如,系统会动态调整内存需求,自动缩减库和增加数据库所占文件的空间大小,自动更新统计数据等等。
(3)新的Enterprise Manager它以MMC(Microsoft Management Console)为基础加以设计,其界面和其他微软服务器产品一致,看上去很像Windows的资源管理器。
(4)简化了SQL Server 2000数据库与Windows文件系统之间的关系,具有更好的可伸缩性在SQL Server 2000中,数据库驻留在操作系统文件上,而不再位于SQL Server的逻辑设备中,取消了以前必须先建立设备(Device),再在设备上建立数据库的观念,现在仅使用CREATE DATABASE 语句即可创建数据库及其所有文件,从而简化了数据库设计和管理的工作。
SQL Server 使用指南说明书

1. What are the two authentication modes in SQL Server?There are two authentication modes –•Windows Mode•Mixed ModeModes can be changed by selecting the tools menu of SQL Server configuration properties and choose security page.2. What Is SQL Profiler?SQL Profiler is a tool which allows system administrator to monitor events in the SQL server. This is mainly used to capture and save data about each event of a file or a table for analysis.3. What is recursive stored procedure?SQL Server supports recursive stored procedure which calls by itself. Recursive stored procedure can be defined as a method of problem solving wherein the solution is arrived repetitively. It can nest up to 32 levels.CREATE PROCEDURE [dbo].[Fact](@Number Integer,@RetVal Integer OUTPUT)ASDECLARE @In IntegerDECLARE @Out IntegerIF @Number != 1BEGINSELECT @In = @Number – 1EXEC Fact @In, @Out OUTPUT - Same stored procedure has been called again(Recursively) SELECT @RetVal = @Number * @OutENDELSEBEGINSELECT @RetVal = 1ENDRETURNGO4. What are the differences between local and global temporary tables?•Local temporary tables are visible when there is a connection, and are deleted when the connection is closed.CREATE TABLE #<tablename>•Global temporary tables are visible to all users, and are deleted when the connection that created it is closed.CREATE TABLE ##<tablename>5. What is CHECK constraint?A CHECK constraint can be applied to a column in a table to limit the values that can be placed in a column. Check constraint is to enforce integrity.6. Can SQL servers linked to other servers?SQL server can be connected to any database which has OLE-DB provider to give a link. Example: Oracle has OLE-DB provider which has link to connect with the SQL server group.7. What is sub query and its properties?A sub-query is a query which can be nested inside a main query like Select, Update, Insert or Delete statements. This can be used when expression is allowed. Properties of sub query can be defined as• A sub query should not have order by clause• A sub query should be placed in the right hand side of the comparison operator of the main query• A sub query should be enclosed in parenthesis because it needs to be executed first before the main query•More than one sub query can be included8. What are the types of sub query?There are three types of sub query –•Single row sub query which returns only one row•Multiple row sub query which returns multiple rows•Multiple column sub query which returns multiple columns to the main query. With that sub query result, Main query will be executed.9. What is SQL server agent?The SQL Server agent plays a vital role in day to day tasks of SQL server administrator(DBA). Serv er agent’s purpose is to implement the tasks easily with the scheduler engine which allows our jobs to run at scheduled date and time.10. What are scheduled tasks in SQL Server?Scheduled tasks or jobs are used to automate processes that can be run on a scheduled time at a regular interval. This scheduling of tasks helps to reduce human intervention during night time and feed can be done at a particular time. User can also order the tasks in which it has to be generated.11. What is COALESCE in SQL Server?COALESCE is used to return first non-null expression within the arguments. This function is used to return a non-null from more than one column in the arguments.Example –Select COALESCE(empno, empname, salary) from employee;12. How exceptions can be handled in SQL Server Programming?Exceptions are handled using TRY----CATCH constructs and it is handles by writing scripts inside the TRY block and error handling in the CATCH block.13. What is the purpose of FLOOR function?FLOOR function is used to round up a non-integer value to the previous least integer. Example is givenFLOOR(6.7)Returns 6.14. Can we check locks in database? If so, how can we do this lock check?Yes, we can check locks in the database. It can be achieved by using in-built stored procedure called sp_lock.15. What is the use of SIGN function?SIGN function is used to determine whether the number specified is Positive, Negative and Zero. This will return +1,-1 or 0.Example –SIGN(-35) returns -116. What is a Trigger?Triggers are used to execute a batch of SQL code when insert or update or delete commands are executed against a table. Triggers are automatically triggered or executed when the data is modified. It can be executed automatically on insert, delete and update operations.17. What are the types of Triggers?There are four types of triggers and they are:•Insert•Delete•Update•Instead of18. What is an IDENTITY column in insert statements?IDENTITY column is used in table columns to make that column as Auto incremental number or a surrogate key.19. What is Bulkcopy in SQL?Bulkcopy is a tool used to copy large amount of data from Tables. This tool is used to load large amount of data in SQL Server.20. What will be query used to get the list of triggers in a database?Query to get the list of triggers in database-Select * from sys.objects where type=’tr’21. What is the difference between UNION and UNION ALL?• UNION: To select related information from two tables UNION command is used. It is similar to JOIN command.• UNION All: The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values. It will not remove duplicate rows, instead it will retrieve all rows from all tables.22. How Global temporary tables are represented and its scope?Global temporary tables are represented with ## before the table name. Scope will be the outside the session whereas local temporary tables are inside the session. Session ID can be found using @@SPID.23. What are the differences between Stored Procedure and the dynamic SQL?Stored Procedure is a set of statements which is stored in a compiled form. Dynamic SQL is a set of statements that dynamically constructed at runtime and it will not be stored in a Database and it simply execute during run time.24.What is Collation?Collation is defined to specify the sort order in a table. There are three types of sort order –1.Case sensitive2.Case Insensitive3.Binary25. How can we get count of the number of records in a table?Following are the queries can be used to get the count of records in a table -Select * from <tablename> Select count(*) from <tablename> Select rows from sysindexes where id=OBJECT_ID(tablename) and indid<226. What is the command used to get the version of SQL Server?Select SERVERPROPERTY(‘productversion’)is used to get the version of SQL Server.27. What is UPDATE_STATISTICS command?UPDATE_STATISTICS command is used to update the indexes on the tables when there is a large amount of deletions or modifications or bulk copy occurred in indexes.28. What is the use of SET NOCOUNT ON/OFF statement?By default, NOCOUNT is set to OFF and it returns number of records got affected whenever the command is getting executed. If the user doesn’t want to display the number of records affected, it can be explicitly set to ON- (SET NOCOUNT ON).29. Which SQL server table is used to hold the stored procedure scripts?Sys.SQL_Modules is a SQL Server table used to store the script of stored procedure. Name of the stored procedure is saved in the table called Sys.Procedures.30. What are Magic Tables in SQL Server?During DML operations like Insert, Delete, and Update SQL Server create magic tables to hold the values during the DML operations. These magic tables are used inside the triggers for data transaction.31. What is the difference between SUBSTR and CHARINDEX in the SQL Server?The SUBSTR function is used to return specific portion of string in a given string. But, INSTR function gives character position in a given specified string.SUBSTR(“Smiley”,3)Gives result as SmiCHARINDEX(“Smiley”,’i’,1)Gives 3 as result as I appears in 3rd position of the string32. What is the use of =,==,=== operators?= is used to assign one value or variable to another variable. == is used for comparing two strings or numbers. === is used to compare only string with the string and number with numbers.33. What is ISNULL() operator?ISNULL function is used to check whether value given is NULL or not NULL in sql server. This function also provides to replace a value with the NULL.34. What is the use of FOR Clause?FOR clause is mainly used for XML and browser options. This clause is mainly used to display the query results in XML format or in browser.35. What will be the maximum number of index per table?For SQL Server 2008 100 Index can be used as maximum number per table. 1 Clustered Index and 999 Non-clustered indexes per table can be used in SQL Server.1000 Index can be used as maximum number per table. 1 Clustered Index and 999 Non-clustered indexes per table can be used in SQL Server.1 Clustered Index and 999 Non-clustered indexes per table can be used in SQL Server.36. What is the difference between COMMIT and ROLLBACK?Every statement between BEGIN and COMMIT becomes persistent to database when the COMMIT is executed. Every statement between BEGIN and ROOLBACK are reverted to the state when the ROLLBACK was executed.37. What is the difference between varchar and nvarchar types?Varchar and nvarchar are same but the only difference is that nvarhcar can be used to store Unicode characters for multiple languages and it also takes more space when compared with varchar.38. What is the use of @@SPID?A @@SPID returns the session ID of the current user process.39. What is the command used to Recompile the stored procedure at run time?Stored Procedure can be executed with the help of keyword called RECOMPILE.ExampleExe <SPName> WITH RECOMPILEOr we can include WITHRECOMPILE in the stored procedure itself.40. How to delete duplicate rows in SQL Server?Duplicate rows can be deleted using CTE and ROW NUMER feature of SQL Server.41. Where are SQL Server user names and passwords stored in SQL Server?User Names and Passwords are stored in sys.server_principals and sys.sql_logins. But passwords are not stored in normal text.42. What is the difference between GETDATE and SYSDATETIME?Both are same but GETDATE can give time till milliseconds and SYSDATETIME can give precision till nanoseconds. SYSDATE TIME is more accurate than GETDATE.43. How data can be copied from one table to another table?INSERT INTO SELECTThis command is used to insert data into a table which is already created.SELECT INTOThis command is used to create a new table and its structure and data can be copied from existing table.44. What is TABLESAMPLE?TABLESAMPLE is used to extract sample of rows randomly that are all necessary for the application. The sample rows taken are based on the percentage of rows.45. Which command is used for user defined error messages?RAISEERROR is the command used to generate and initiates error processing for a given session. Those user defined messages are stored in sys.messages table.46. What do mean by XML Datatype?XML data type is used to store XML documents in the SQL Server database. Columns and variables are created and store XML instances in the database.47. What is CDC?CDC is abbreviated as Change Data Capture which is used to capture the data that has been changed recently. This feature is present in SQL Server 2008.48. What is SQL injection?SQL injection is an attack by malicious users in which malicious code can be inserted into strings that can be passed to an instance of SQL server for parsing and execution. All statements have to checked for vulnerabilities as it executes all syntactically valid queries that it receives.Even parameters can be manipulated by the skilled and experienced attackers.49. What are the methods used to protect against SQL injection attack?Following are the methods used to protect against SQL injection attack:•Use Parameters for Stored Procedures•Filtering input parameters•Use Parameter collection with Dynamic SQL•In like clause, user escape characters50. What is Filtered Index?Filtered Index is used to filter some portion of rows in a table to improve query performance, index maintenance and reduces index storage costs. When the index is created with WHERE clause, then it is called Filtered IndexGuru99 Provides FREE ONLINE TUTORIAL on Various courses likeJenkins Agile Testing RPA JUnitSoftware EngineeringSelenium CCNA AngularJS NodeJS PLSQL。
sqlserver常用命令

sqlserver常用命令SQLServer是一种关系型数据库管理系统,被广泛应用于各种企业级应用程序中。
它提供了一系列的命令,用于管理数据库、表、视图、存储过程等对象。
本文将介绍SQL Server中常用的命令及其使用方法,帮助读者快速掌握SQL Server的基本操作。
一、数据库管理命令1. 创建数据库CREATE DATABASE database_name;该命令用于创建一个新的数据库,其中database_name为要创建的数据库名称。
使用该命令时,需要确保具有足够的权限。
2. 删除数据库DROP DATABASE database_name;该命令用于删除指定的数据库,其中database_name为要删除的数据库名称。
使用该命令时,需要确保具有足够的权限,并且要谨慎操作,以免误删数据。
3. 修改数据库ALTER DATABASE database_name SET options;该命令用于修改指定的数据库,其中options为要修改的选项。
常用的选项包括修改数据库的名称、修改数据库的文件路径、修改数据库的恢复模式等。
二、表管理命令1. 创建表CREATE TABLE table_name (column_name1 data_type1, column_name2 data_type2, …);该命令用于创建一个新的表,其中table_name为要创建的表名称,column_name为要创建的列名称,data_type为要创建的列数据类型。
使用该命令时,需要确保具有足够的权限。
2. 删除表DROP TABLE table_name;该命令用于删除指定的表,其中table_name为要删除的表名称。
使用该命令时,需要确保具有足够的权限,并且要谨慎操作,以免误删数据。
3. 修改表ALTER TABLE table_name ADD column_name data_type;该命令用于向指定的表中添加一列,其中table_name为要修改的表名称,column_name为要添加的列名称,data_type为要添加的列数据类型。
SQL Server 常用操作手册

一、建库操作
1.打开企业管理器;
2.选中数据库节点,进行新建;
3.弹出数据库属性,给数据库命名,使用英文;
4.右键刷新数据库,新建数据库就完成了二、建表操作
方法一、在数据库右键----新建----表
方法二、在数据库---选择表---右键---新建表
三、设主键操作
1.右键单击表—设计表
2.选中列---点击设置主键
四、设外键操作
1.右键单击表—设计表
2.在表空白处右键,单击索引/键
3.弹出属性对对话框---关系选项
4.分别设置主键表、外键表以及主键,在外键表下拉列表—选择对应的主键,即是外键
五、备份操作
1.右键单击数据库—所有任务----备份数据库
2.弹出SQL Server备份,选择存储地址,点击确定
六、还原操作
1.新建一个数据库,右键单击数据库---所有任务---还原数据库,如图:
2.弹出还原数据库对话框,选择“从设备”选项,选好地址;
七、导入/导出操作
1.右键点击数据库,选择所有任务---导入/导出数据
2.弹出导入/导出操作对话框,进行下一步。
八、去掉系统对象
Local---右键编辑。
sql server 使用方法(一)

SQL Server 使用方法SQL Server是一种关系数据库管理系统,为企业提供了强大的数据管理和分析能力。
在本文中,我们将详细介绍SQL Server的使用方法,包括安装、配置、管理和优化等方面。
安装SQL Server1. 下载SQL Server安装程序首先,您需要从官方网站下载SQL Server的安装程序,选择适合您环境的版本和版本号。
2. 运行安装程序运行下载的安装程序,并按照提示逐步完成安装过程。
在安装过程中,您需要选择安装类型、实例名称、安装路径等信息。
3. 配置SQL Server安装完成后,您需要配置SQL Server,包括设置服务器名称、身份验证模式、端口等信息。
管理SQL Server1. 连接到SQL Server使用SQL Server Management Studio(SSMS)工具,您可以连接到SQL Server实例,进行数据库管理和查询操作。
2. 创建数据库通过SSMS工具,您可以创建新的数据库,设置数据库的名称、文件路径、日志文件等参数。
3. 管理数据库对象在SSMS中,您可以管理数据库对象,包括表、视图、存储过程、触发器等。
优化SQL Server1. 索引优化通过创建合适的索引,可以提高数据库的查询性能。
您可以使用SSMS工具分析查询执行计划,确定需要创建的索引类型和字段。
2. 查询优化通过优化查询语句,可以减少数据库的负载,提高查询性能。
您可以使用SSMS工具分析慢查询,优化查询语句的结构和索引使用。
3. 系统配置优化通过调整SQL Server的系统配置参数,可以提高数据库的整体性能。
您可以通过SSMS工具修改服务器级别的配置参数,如内存分配、并发连接数等。
总结在本文中,我们详细介绍了SQL Server的使用方法,包括安装、配置、管理和优化等方面。
通过掌握这些方法,您可以更好地使用SQL Server,提高数据库的性能和可靠性,满足企业需求。
sqlserver基本操作

SQLserver 学习笔记------------------------------创建数据库-------------------------create database ckglon primary --设置文件组第一个为默认文件组即主要文件组(--创建第一个数据文件,第一个数据文件是主文件name = xkgldata1, --设置名字filename = 'D:\java\Databank\DATA\xkgldata1.mdf', --设置路径要加上文件名字不要忘了最后要打逗号size = 10, --设置初始文件的大小不写默认单位是MBmaxsize = 500, --设置文件的最大值filegrowth = 5 --设置文件的增长率),(--创建第二个数据文件,后缀名要改成“ndf”name = xkgldata2,filename = 'D:\java\Databank\DATA\xkgldata2.ndf',size = 10,maxsize = 500,filegrowth = 5)log on --创建日志文件(name = xkg1_log,filename = 'D:\java\Databank\DATA\xkgllog.ldf',size = 3,filegrowth = 10%)--修改一般用“alter database + 数据库名字”--修改数据库名字alter database ckgl modify name = xkgl--修改数据库里面的主要数据文件alter database xkgl modify file(name = xkgldata1,newname = xkglmdata)--增加一个数据文件alter database xkgl add file(name = xkgldata3,filename = 'D:\java\Databank\DATA\xkgldata3.ndf',size = 10,maxsize = 500,filegrowth = 5)--添加文件组alter database xkgl add filegroup myfg--删除文件组alter database xkgl remove filegroup myfg--增加一个数据文件到某个文件组alter database xkgl add file(name = xkgldata4,filename = 'D:\java\Databank\DATA\xkgldata4.ndf',size = 10,maxsize = 500,filegrowth = 5)to filegroup myfg--删除一个数据文件alter database xkgl remove file xkgldata4--添加日志文件alter database xkgl add log file(name = xkgld_lg2,filename = 'D:\java\Databank\DATA\xkglla2.ldf',size = 3,filegrowth = 10%)--删除日志文件alter database xkgl remove file xkgld_lg2--更改数据文件的大小或日志文件的大小alter database xkgl modify file(name = xkgldata3,size = 11MB)/*移动数据文件或日志文件,需要先将数据文件设置为脱机状态,然后移动文件到想要的路径,然后用SQL命令设置数据文件到目标路径,然后把数据库设置为联机状态*/alter database xkgl set offlinealter database xkgl modify file(name = xkglmdata,filename = 'D:\java\Database\DATA\xkgldata1.mdf')alter database xkgl modify file(name = xkgldata2,filename = 'D:\java\Database\DATA\xkgldata2.ndf')alter database xkgl modify file(name = xkgldata3,filename = 'D:\java\Database\DATA\xkgldata3.ndf')alter database xkgl modify file(name = xkgldata4,filename = 'D:\java\Database\DATA\xkgldata4.ndf')alter database xkgl modify file(name = xkg1_log,filename = 'D:\java\Database\DATA\xkgllog.ldf')alter database xkgl set onlinealter database xkgl modify file(name = xkg1_log,newname = xkgl_log)alter database xkgl modify file(name = xkglmdata,newname = xkgldata1)--删除数据库drop database xkgl----------------------------数据库表的创建----------------------------创建数据表use class --选择数据库gocreate table Department --创建表(DepartmentID char(4) primary key, --primary key 是设置主键DepartmentName varchar(20) not null unique, --unique是设置唯一DepartmentHeader varchar(8) not null, --not null 是非空TeacherNum int)use classgocreate table Class(ClassID char(8) primary key,ClassName varchar(20) not null,Monitor char(8),StudentNum int check(StudentNum >= 0), --check约束DepartmentID char(4) foreign key references Department(DepartmentID), --foreign key 定义外键references用于指定外键所引用的表及表的主键)use classgocreate table Student(StudentID char(12) primary key,StudentName char(8) not null,Sex char(2) not null check(Sex = '男' or Sex = '女'),Birth date not null,HomeAddr varchar(80),EntranceTime date default getdate(), -- getdate()是得到系统时间的方法ClassID char(8) references Class(ClassID) --行级约束时可以省略foreign key)create table Course(CourseID char(8) primary key,CourseNmae varchar(60) not null,BookName varchar(80) not null,Credit int not null)create table Grade(CourseID char(8) references Course(CourseID),StudentID char(12) references Student(StudentID),Semester int not null,SchoolYear int,Grade numeric(5,1) check(Grade>= 0),primary key(CourseID, StudentID) --在定义完CourseID和StudentID列后定义主键约束,这种约束为表级约束)use classgocreate table Schedule(TeacherID char(8) references Teacher(TeacherID),CourseID char(8) references Course(CourseID),ClassID char(8) references Class(ClassID),Semester int not null,SchoolYear int not null,ScheduleIdent varchar(40) not null,Classroom varchar(20) not nullprimary key(TeacherID, CourseID, ClassID))/*非空not null唯一unique默认default 默认值检查check (约束表达式)外键reference 表名或列名标示identity (起始值,增量)*/====================================================================---------------------------------表的修改---------------------------use testgocreate table goods(goodsID varchar(10) primary key,goodsName varchar(15) not null,price decimal(6,2) check(price > 0),total int check(total >= 0),supplier varchar(20)-----------------------用T—SQL语句修改表---------------------------- --格式alter table 表名add 列名数据类型约束--添加列alter column 列名数据类型--修改列drop column 列名--删除列--列在userinfo表中添加一列code(邮编)char()use xkglgoalter table userinfoadd code char(6)-----------------------查看表属性信息-------------------------sp_help 对象名sp_help userinfo-----------------------------数据查询-------------------------------格式select 列名from 表名-- * 代表所有列--列查询学生表的所有信息select * from Student--指定列--列查询所有学生的姓名与性别,先写哪个列就先显示哪个列select StudentName, Sex from Studentselect Sex, StudentName from Student--练习查询所有课程的名称与学分select CourseName, Credit from Course--运算列--列把所有成绩+10select CourseID, StudentID, Grade, Grade+10from Grade--用+连接字符串--列select StudentName+'您好' +Sexfrom Student--使用系统函数year() getdate()--别名--列名as '列标题' (as关键字可省)--‘列标题’== 列名--列select CourseID '课程号', StudentID as 学号, 成绩=Grade+10 from Grade--增加说明列--例select StudentName, '的性别是:',Sexfrom Student--行的选择select StudentName, '的性别是:',Sexfrom Studentwhere Sex = '男'--------------------行的检索-------------------------------------------比较运算符= > < <>--查询学生张三的姓名与性别select StudentName, Sex 性别from Studentwhere StudentName = '张三'--逻辑运算符and or not--查询年以后出生的男生的信息select *from Studentwhere year(Birth) >= 1992 and Sex = '男'--查询范围--列名between 最小值and 最大值--等价于:列名>= 最小值and 列名<= 最大值--查询成绩在-80之间的成绩信息select *from Gradewhere grade between 70 and 80--查询列表--列名in(值,值。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
sql server学习笔记1、说明:创建数据库CREATE DATABASE database-name2、说明:删除数据库drop database dbname3、说明:备份sql server--- 创建备份数据的deviceUSE masterEXEC sp_addumpdevice 'disk', 'testBack', 'c:mssql7backupMyNwind_1.dat'--- 开始备份BACKUP DATABASE pubs TO testBack4、说明:创建新表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 only5、说明:删除新表:drop table tabname6、说明:增加一个列: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 viewname10、说明:几个简单的基本的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 table111、说明:几个高级查询运算词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.cB:right outer join:右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。
C:full outer join:全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。
其次,大家来看一些不错的sql语句1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用)法一:select * into b from a where 1<>1法二:select top 0 * into b from a2、说明:拷贝表(拷贝数据,源表名: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,ername,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b6、说明:外连接查询(表名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.c7、说明:在线视图查询(表名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 time2select a,b,c, from table1 where a not between 数值1 and 数值29、说明: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())>513、说明:一条sql 语句搞定数据库分页select top 10 b.* from (select top 20 主键字段,排序字段from 表名order by 排序字段desc) a,表名b where b.主键字段= a.主键字段order by a.排序字段14、说明:前10条记录select top 10 * form table1 where 范围15、说明:选择在每一组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、说明:删除重复记录Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)20、说明:列出数据库里所有的表名select name from sysobjects where type='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 323、说明:初始化表table1TRUNCATE TABLE table124、说明:选择从10到15的记录select top 5 * from (select top 15 * from table order by id asc) table_别名order by id desc随机选择数据库记录的方法(使用Randomize函数,通过SQL语句实现)对存储在数据库中的数据来说,随机数特性能给出上面的效果,但它们可能太慢了些。