SQL Statements and Data for SQL Server
SQL Server 权限管理手册说明书
Top Level Server PermissionsDatabase Level PermissionsALTER ANY APPLICATION ROLE ALTER ANY ASSEMBLY ALTER ANY ASYMMETRIC KEY ALTER ANY CERTIFICATE ALTER ANY CONTRACTALTER ANY DATABASE AUDIT ALTER ANY DATABASE DDL TRIGGERALTER ANY DATABASE EVENT NOTIFICATION ALTER ANY DATASPACEALTER ANY FULLTEXT CATALOGALTER ANY MESSAGE TYPEALTER ANY REMOTE SERVICE BINDING ALTER ANY ROLE ALTER ANY ROUTE ALTER ANY SCHEMA ALTER ANY SERVICE ALTER ANY SYMMETRIC KEYALTER ANY USER –See Connect and Authentication –Database Permissions ChartCREATE AGGREGATE CREATE DEFAULT CREATE FUNCTION CREATE PROCEDURE CREATE QUEUE CREATE RULE CREATE SYNONYM CREATE TABLE CREATE TYPE CREATE VIEWCREATE XML SCHEMA COLLECTIONTop Level Database PermissionsCONTROL ON DATABASE::<name>CREATE ASSEMBLY CREATE ASYMMETRIC KEY CREATE CERTIFICATE CREATE CONTRACTCREATE DATABASE DDL EVENT NOTIFICATIONCREATE FULLTEXT CATALOG CREATE MESSAGE TYPECREATE REMOTE SERVICE BINDING CREATE ROLE CREATE ROUTE CREATE SCHEMA CREATE SERVICE CREATE SYMMETRIC KEYAUTHENTICATE BACKUP DATABASE BACKUP LOG CHECKPOINTCONNECT REPLICATION DELETE EXECUTE INSERT REFERENCES SELECT UPDATEVIEW DEFINITION TAKE OWNERSHIP SHOWPLANSUBSCRIBE QUERY NOTIFICATIONS VIEW DATABASE STATECONTROL SERVERCONNECT DATABASESTATEMENTS:CREATE DATABASE AUDIT SPECIFICATION CREATE/ALTER/DROP database triggersPARTITION & PLAN GUIDE statementsSTATEMENTS:Combined with TRUSTWORTHY allows delegation of authentication BACKUP DATABASE BACKUP LOG CHECKPOINTCREATE ANY DATABASE ALTER ANY DATABASEALTER ANY SERVER AUDIT ALTER ANY EVENT NOTIFICATIONAUTHENTICATE SERVERVIEW ANY DEFINITIONALTER TRACEVIEW SERVER STATE STATEMENTS:Applies to subordinate objects in the database. See Database Permissions –Schema Objects chart.TAKE OWNERSHIP ON OBJECT|TYPE|XML SCHEMA COLLECTION::<name>RECEIVE ON OBJECT::<queue name>SELECT ON OBJECT::<queue name>VIEW CHANGE TRACKING ON OBJECT::<name> SELECT ON OBJECT::<table |view name>INSERT ON OBJECT::< table |view name> UPDATE ON OBJECT::< table |view name> DELETE ON OBJECT::< table |view name>EXECUTE ON OBJECT|TYPE|XML SCHEMA COLLECTION::<name> REFERENCES ON OBJECT|TYPE|XML SCHEMA COLLECTION:<name> VIEW DEFINITION ON OBJECT|TYPE|XML SCHEMA COLLECTION::<name>ALTER ON OBJECT|TYPE|XML SCHEMA COLLECTION::<name>TAKE OWNERSHIP ON SCHEMA::<name>VIEW CHANGE TRACKING ON SCHEMA::<name>SELECT ON SCHEMA::<name>INSERT ON SCHEMA::<name>UPDATE ON SCHEMA::<name>DELETE ON SCHEMA::<name>EXECUTE ON SCHEMA::<name>REFERENCES ON SCHEMA::<name>VIEW DEFINITION ON SCHEMA::<name>ALTER ON SCHEMA::<name>CREATE SEQUENCESELECT ON DATABASE::<name>INSERT ON DATABASE::<name>UPDATE ON DATABASE::<name>DELETE ON DATABASE::<name>EXECUTE ON DATABASE::<name>REFERENCES ON DATABASE::<name>VIEW DEFINITION ON DATABASE::<name>TAKE OWNERSHIP ON DATABASE::<name>ALTER ON DATABASE::<name>ALTER ANY SCHEMACREATE SCHEMACREATE AGGREGATE CREATE DEFAULT CREATE FUNCTION CREATE PROCEDURE CREATE QUEUE CREATE RULE CREATE SYNONYM CREATE TABLE CREATE TYPE CREATE VIEWCREATE XML SCHEMA COLLECTIONVIEW ANY DEFINITIONVIEW ANY DATABASEALTER ANY DATABASEServer PermissionsDatabase PermissionsSchema PermissionsObject Permissions Type PermissionsXML Schema Collection PermissionsDatabase Permissions –Schema ObjectsNotes:•To create a schema object (such as a table) you must have CREATE permission for that object type plus ALTER ON SCHEMA::<name> for the schema of the object. Might require REFERENCES ON OBJECT::<name> for any referenced CLR type or XML schema collection.•To alter an object (such as a table) you must have ALTER permission on the object (or schema ),or CONTROL permission on the object.CONTROL ON SERVERCONTROL ON DATABASE::<name>CONTROL ON SCHEMA ::<name>CONTROL ON OBJECT|TYPE|XML SCHEMA COLLECTION ::<name>OBJECT permissions apply to the following database objects:AGGREGATE DEFAULT FUNCTION PROCEDURE QUEUE RULE SYNONYM TABLE VIEW(All permissions do not apply to all objects. For example UPDATE only applies to tables and views.)•To drop an object (such as a table) you must have ALTER permission on the schema or CONTROL permission on the object.•To create an index requires ALTER OBJECT::<name> permission on the table or view.•To create or alter a trigger on a table or view requires ALTER OBJECT::<name> on the table or view.•To create statistics requires ALTER OBJECT::<name> on the table or view.CONTROL SERVERVIEW ANY DEFINITIONALTER ANY DATABASECONTROL ON DATABASE::<name>VIEW DEFINITION ON DATABASE::<name>REFERENCES ON DATABASE::<name>ALTER ON DATABASE::<name>ALTER ANY FULLTEXT CATALOGCREATE FULLTEXT CATALOG Certificate PermissionsFull-text PermissionsAssembly PermissionsQuestions and comments to ************************Server Role PermissionsCONTROL SERVERVIEW ANY DEFINITIONALTER ANY SERVER ROLEVIEW DEFINITION ON SERVER ROLE::<name>TAKE OWNERSHIP ON SERVER ROLE::<name>ALTER ON SERVER ROLE::<name>CONTROL ON SERVER ROLE::<name>Most permission statements have the format :AUTHORIZATION PERMISSION ON SECURABLE::NAME TO PRINCIPAL•AUTHORIZATION must be GRANT, REVOKE or DENY.•PERMISSION is listed in the charts below.•ON SECURABLE::NAME is the server, server object, database, or database object and its name. Some permissions do not require ON SECURABLE::NAME.•PRINCIPAL is the login, user, or role which receives or loses the permission. Grant permissions to roles whenever possible.Sample grant statement: GRANT UPDATE ON OBJECT::Production.Parts TO PartsTeam Denying a permission at any level, overrides a related grant.To remove a previously granted permission, use REVOKE, not DENY.NOTES:•The CONTROL SERVER permission has all permissions on the instance of SQL Server.•The CONTROL DATABASE permission has all permissions on the database.•Permissions do not imply role memberships and role memberships do not grant permissions. (E.g. CONTROL SERVER does not imply membership in the sysadmin fixed server role. Membership in the db_owner role does not grant the CONTROL DATABASE permission.) However, it is sometimes possible to impersonate between roles and equivalent permissions.•Granting any permission on a securable allows VIEW DEFINITION on that securable. It is an implied permissions and it cannot be revoked, but it can be explicitly denied by using the DENY VIEW DEFINITION statement.Server Level PermissionsNotes:•Creating a full-text index requires ALTER permission on the table and REFERENCES permission on the full-text catalog.•Dropping a full-text index requires ALTER permission on the table.STATEMENTS:DROP DATABASEMarch 28, 2014How to Read this Chart•Most of the more granular permissions are included in more than one higher level scope permission. So permissions can be inherited from more than one type of higher scope.•Black, green, and blue arrows and boxes point to subordinate permissions that are included in the scope of higher a level permission.•Brown arrows and boxes indicate some of the statements that can use the permission.CREATE SERVER ROLEAvailability Group PermissionsCONTROL SERVERVIEW ANY DEFINITIONALTER ANY AVAILABILITY GROUPVIEW DEFINITION ON AVAILABILITY GROUP::<name>TAKE OWNERSHIP ON AVAILABILITY GROUP::<name>ALTER ON AVAILABILITY GROUP::<name>CONTROL ON AVAILABILITY GROUP::<name>CREATE AVAILABILITY GROUPADMINISTER BULK OPERATIONSALTER ANY AVAILABILITY GROUP –See Availability Group PermissionsCREATE AVAILABILTY GROUPALTER ANY CONNECTION ALTER ANY CREDENTIALALTER ANY DATABASE –See Database Permission ChartsCREATE ANY DATABASE –See Top Level Database PermissionsALTER ANY ENDPOINT –See Connect and AuthenticationCREATE ENDPOINT –See Connect and AuthenticationALTER ANY EVENT NOTIFICATIONCREATE DDL EVENT NOTIFICATION CREATE TRACE EVENT NOTIFICATIONALTER ANY EVENT SESSION ALTER ANY LINKED SERVERALTER ANY LOGIN –See Connect and Authentication ALTER ANY SERVER AUDITALTER ANY SERVER ROLE –See Server Role PermissionsCREATE SERVER ROLE –See Server Role PermissionsALTER RESOURCES (Not used. Use diskadmin fixed server role instead.)ALTER SERVER STATEVIEW SERVER STATEALTER SETTINGS ALTER TRACEAUTHENTICATE SERVERCONNECT SQL –See Connect and Authentication CONNECT ANY DATABASE IMPERSONATE ANY LOGIN SELECT ALL USER SECURABLES SHUTDOWN UNSAFE ASSEMBLYEXTERNAL ACCESS ASSEMBLYVIEW ANY DEFINITIONVIEW ANY DATABASE –See Database Permissions –Schema* NOTE:The SHUTDOWN statement requires the SQL Server SHUTDOWN permission. Starting, stopping, and pausing the Database Engine from SSCM, SSMS, or Windows requires Windows permissions, not SQL Server permissions.STATEMENTS:CREATE/ALTER/DROP server triggers OPENROWSET(BULK….KILL CREATE/ALTER/DROP CREDENTIAL DBCC FREE…CACHE and SQLPERF SELECT on server-level DMV’s sp_configure, RECONFIGURE sp_create_traceAllows server-level delegationCONTROL SERVERSTATEMENTS:CREATE/ALTER/DROP server triggers OPENROWSET(BULK …KILLServer scoped event notifications Server scoped DDL event notifications Event notifications on trace events Extended event sessions sp_addlinkedserverDBCC FREE…CACHE and SQLPERF SELECT on server-level DMV’s sp_configure, RECONFIGURE sp_trace_create Allows server-level delegation SHUTDOWN*CREATE/ALTER/DROP SERVER AUDIT and SERVER AUDIT SPECIFICATION CONTROL SERVERVIEW ANY DEFINITION ALTER ANY LOGINCONNECT SQLCONTROL ON LOGIN::<name>Connect and Authentication –Server PermissionsVIEW ANY DEFINITIONALTER ANY ENDPOINTCREATE ENDPOINTCONNECT ON ENDPOINT::<name>TAKE OWNERSHIP ON ENDPOINT::<name>VIEW DEFINITION ON ENDPOINT::<name>ALTER ON ENDPOINT::<name>CONTROL ON ENDPOINT::<name>Notes:•The CREATE LOGIN statement creates a login and grants CONNECT SQL to that login.•Enabling a login (ALTER LOGIN <name> ENABLE) is not the same as granting CONNECT SQL permission.•To map a login to a credential, see ALTER ANY CREDENTIAL.•When contained databases are enabled, users can access SQL Server without a login. See database user permissions.•To connect using a login you must have :o An enabled login o CONNECT SQLoCONNECT for the database (if specified)VIEW DEFINITION ON LOGIN::<name>IMPERSONATE ON LOGIN::<name>ALTER ON LOGIN::<name>STATEMENTS:ALTER LOGIN, sp_addlinkedsrvlogin DROP LOGIN CREATE LOGINSTATEMENTS:ALTER ENDPOINT DROP ENDPOINTCREATE ENDPOINTSTATEMENTS:ALTER SERVER ROLE <name> ADD MEMBER DROP SERVER ROLECREATE SERVER ROLESTATEMENTS:ALTER AVAILABILITY GROUP DROP AVAILABILITY GROUPCREATE AVAILABILITY GROUPCONTROL ON FULLTEXT CATALOG::<name>VIEW DEFINITION ON FULLTEXT CATALOG::<name>REFERENCES ON FULLTEXT CATALOG::<name>TAKE OWNERSHIP ON FULLTEXT CATALOG::<name>ALTER ON FULLTEXT CATALOG::<name>STATEMENTS:ALTER FULLTEXT CATALOG CREATE FULLTEXT CATALOGDatabase Role PermissionsCONTROL SERVERVIEW ANY DEFINITIONALTER ANY DATABASEVIEW DEFINITION ON DATABASE::<name>ALTER ON DATABASE::<name>ALTER ANY ROLE CREATE ROLE CONTROL ON DATABASE::<name>VIEW DEFINITION ON ROLE::<name>TAKE OWNERSHIP ON ROLE::<name>ALTER ON ROLE::<name>CONTROL ON ROLE::<name>STATEMENTS:ALTER ROLE <name> ADD MEMBER DROP ROLECREATE ROLESymmetric Key PermissionsCONTROL SERVERVIEW ANY DEFINITIONALTER ANY DATABASEVIEW DEFINITION ON DATABASE::<name>REFERENCES ON DATABASE::<name>ALTER ON DATABASE::<name>ALTER ANY SYMMETRIC KEYCREATE SYMMETRIC KEY CONTROL ON DATABASE::<name>VIEW DEFINITION ON SYMMETRIC KEY::<name>REFERENCES ON SYMMETRIC KEY::<name>TAKE OWNERSHIP ON SYMMETRIC KEY::<name>ALTER ON SYMMETRIC KEY::<name>CONTROL ON SYMMETRIC KEY::<name>STATEMENTS:ALTER SYMMETRIC KEY DROP SYMMETRIC KEY CREATE SYMMETRIC KEYNote: OPEN SYMMETRIC KEY requires VIEW DEFINITION permission on the key (implied by any permission on the key), and requires permission on the key encryption hierarchy.Asymmetric Key PermissionsCONTROL SERVERVIEW ANY DEFINITIONALTER ANY DATABASEVIEW DEFINITION ON DATABASE::<name>REFERENCES ON DATABASE::<name>ALTER ON DATABASE::<name>ALTER ANY ASYMMETRIC KEYCREATE ASYMMETRIC KEYCONTROL ON DATABASE::<name>VIEW DEFINITION ON ASYMMETRIC KEY::<name>REFERENCES ON ASYMMETRIC KEY::<name>TAKE OWNERSHIP ON ASYMMETRIC KEY::<name>ALTER ON ASYMMETRIC KEY::<name>CONTROL ON ASYMMETRIC KEY::<name>STATEMENTS:ALTER ASYMMETRIC KEY DROP ASYMMETRIC KEYCREATE ASYMMETRIC KEYNote: ADD SIGNATURE requires CONTROL permission on the key, andrequires ALTER permission on the object.CONTROL SERVERVIEW ANY DEFINITIONALTER ANY DATABASEVIEW DEFINITION ON DATABASE::<name>REFERENCES ON DATABASE::<name>ALTER ON DATABASE::<name>ALTER ANY CERTIFICATE CREATE CERTIFICATE CONTROL ON DATABASE::<name>VIEW DEFINITION ON CERTIFICATE::<name>REFERENCES ON CERTIFICATE::<name>TAKE OWNERSHIP ON CERTIFICATE::<name>ALTER ON CERTIFICATE::<name>CONTROL ON CERTIFICATE::<name>STATEMENTS:ALTER CERTIFICATE DROP CERTIFICATECREATE CERTIFICATENote: ADD SIGNATURE requiresCONTROL permission on the certificate, and requires ALTER permission on the object.CONTROL SERVERVIEW ANY DEFINITIONALTER ANY DATABASEVIEW DEFINITION ON DATABASE::<name>REFERENCES ON DATABASE::<name>ALTER ON DATABASE::<name>ALTER ANY ASSEMBLY CREATE ASSEMBLYCONTROL ON DATABASE::<name>VIEW DEFINITION ON ASSEMBLY::<name>REFERENCES ON ASSEMBLY::<name>TAKE OWNERSHIP ON ASSEMBLY::<name>ALTER ON ASSEMBLY::<name>CONTROL ON ASSEMBLY::<name>STATEMENTS:ALTER ASSEMBLYDROP ASSEMBLYCREATE ASSEMBLYEvent Notification PermissionsCONTROL SERVERALTER ANY EVENT NOTIFICATIONCREATE DDL EVENT NOTIFICATIONCREATE TRACE EVENT NOTIFICATIONALTER ON DATABASE::<name>ALTER ANY DATABASE EVENT NOTIFICATION CREATE DATABASE DDL EVENT NOTIFICATIONCONTROL ON DATABASE::<name>Database scoped event notificationsDatabase scoped DDL event notificationsEvent notifications on trace eventsNote: EVENT NOTIFICATION permissions also affect service broker. See the service broker chart for more into.Connect and Authentication –Database PermissionsCONTROL SERVERVIEW ANY DEFINITIONALTER ANY DATABASEVIEW DEFINITION ON DATABASE::<name>ALTER ON DATABASE::<name>ALTER ANY USER CONNECT ON DATABASE::<name>CONTROL ON DATABASE::<name>VIEW DEFINITION ON USER::<name>IMPERSONATE ON USER::<name>ALTER ON USER::<name>CONTROL ON USER::<name>STATEMENTS:ALTER USER DROP USER CREATE USERNOTES:•When contained databases are enabled, creating a database user that authenticates at the database, grants CONNECT DATABASE to that user,and it can access SQL Server without a login.•Granting ALTER ANY USER allows a principal to create a user based on a login, but does not grant the server level permission to view information about logins.Replication PermissionsCONTROL SERVERCONTROL ON DATABASE::<name>CONNECT REPLICATION ON DATABASE::<name>CONNECT ON DATABASE::<name>Application Role PermissionsCONTROL SERVERVIEW ANY DEFINITION ALTER ANY DATABASE CONTROL ON DATABASE::<name>VIEW DEFINITION ON DATABASE::<name>ALTER ON DATABASE::<name>ALTER ANY APPLICATION ROLECONTROL ON APPLICATION ROLE::<name>VIEW DEFINITION ON APPLICATION ROLE::<name>ALTER ON APPLICATION ROLE::<name>STATEMENTS:ALTER APPLICATION ROLE DROP APPLICATION ROLE CREATE APPLICATION ROLESTATEMENTS:DROP FULLTEXT CATALOG DROP FULLTEXT STOPLISTDROP FULLTEXT SEARCH PROPERTYLISTCONTROL ON FULLTEXT STOPLIST::<name>VIEW DEFINITION ON FULLTEXT STOPLIST::<name>REFERENCES ON FULLTEXT STOPLIST::<name>TAKE OWNERSHIP ON FULLTEXT STOPLIST::<name>ALTER ON FULLTEXT STOPLIST::<name>STATEMENTS:ALTER FULLTEXT STOPLIST CREATE FULLTEXT STOPLISTCONTROL ON SEARCH PROPERTY LIST::<name>VIEW DEFINITION ON SEARCH PROPERTY LIST::<name>REFERENCES ON SEARCH PROPERTY LIST::<name>TAKE OWNERSHIP ON SEARCH PROPERTY LIST::<name>ALTER ON SEARCH PROPERTY LIST::<name>STATEMENTS:ALTER SEARCH PROPERTY LIST CREATE SEARCH PROPERTY LISTService Broker PermissionsNotes:•The user executing the CREATE CONTRACT statement must have REFERENCES permission on all message typesspecified.•The user executing the CREATE SERVICE statement must have REFERENCES permission on the queue and allcontracts specified.•To execute the CREATE or ALTER REMOTE SERVICE BINDING the user must have impersonate permission forthe principal specified in the statement.•When the CREATE or ALTER MESSAGE TYPE statement specifies a schema collection, the user executing thestatement must have REFERENCES permission on the schema collection specified.•See the ALTER ANY EVENT NOTIFICATION chart for more permissions related to Service Broker.•See the SCHEMA OBJECTS chart for QUEUE permissions.•The ALTER CONTRACT permission exists but at this time there is no ALTER CONTRACT statement.CONTROL ON REMOTE SERVICE BINDING::<name>VIEW DEFINITION ON REMOTE SERVICE BINDING::<name>TAKE OWNERSHIP ON REMOTE SERVICE BINDING::<name>ALTER ON REMOTE SERVICE BINDING::<name>STATEMENTS:ALTER REMOTE SERVICE BINDINGDROP REMOTE SERVICE BINDINGCREATE REMOTE SERVICE BINDINGCONTROL SERVERVIEW ANY DEFINITIONALTER ANY DATABASECONTROL ON DATABASE::<name>VIEW DEFINITION ON DATABASE::<name>ALTER ON DATABASE::<name>ALTER ANY REMOTE SERVICE BINDINGCREATE REMOTE SERVICE BINDINGCONTROL ON CONTRACT::<name>VIEW DEFINITION ON CONTRACT::<name>REFERENCES ON CONTRACT::<name>TAKE OWNERSHIP ON CONTRACT::<name>ALTER ON CONTRACT::<name>STATEMENTS:DROP CONTRACTCREATE CONTRACTCONTROL SERVER VIEW ANY DEFINITIONALTER ANY DATABASECONTROL ON DATABASE::<name>VIEW DEFINITION ON DATABASE::<name>REFERENCES ON DATABASE::<name>ALTER ON DATABASE::<name>ALTER ANY CONTRACTCREATE CONTRACTCONTROL ON SERVICE::<name>VIEW DEFINITION ON SERVICE::<name>SEND ON SERVICE::<name>TAKE OWNERSHIP ON SERVICE::<name>ALTER ON SERVICE::<name>STATEMENTS:ALTER SERVICE DROP SERVICECREATE SERVICECONTROL SERVERVIEW ANY DEFINITION ALTER ANY DATABASE CONTROL ON DATABASE::<name>VIEW DEFINITION ON DATABASE::<name>ALTER ON DATABASE::<name>ALTER ANY SERVICECREATE SERVICESTATEMENTS:ALTER ROUTE DROP ROUTE CREATE ROUTECONTROL SERVERVIEW ANY DEFINITIONALTER ANY DATABASECONTROL ON DATABASE::<name>VIEW DEFINITION ON DATABASE::<name>ALTER ON DATABASE::<name>ALTER ANY ROUTECREATE ROUTE CONTROL ON ROUTE::<name>VIEW DEFINITION ON ROUTE::<name>TAKE OWNERSHIP ON ROUTE::<name>ALTER ON ROUTE::<name>STATEMENTS:ALTER MESSAGE TYPEDROP MESSAGE TYPE CREATE MESSAGE TYPECONTROL SERVER VIEW ANY DEFINITIONALTER ANY DATABASECONTROL ON DATABASE::<name>VIEW DEFINITION ON DATABASE::<name>REFERENCES ON DATABASE::<name>ALTER ON DATABASE::<name>ALTER ANY MESSAGE TYPECREATE MESSAGE TYPECREATE QUEUECONTROL ON MESSAGE TYPE::<name>VIEW DEFINITION ON MESSAGE TYPE::<name>REFERENCES ON MESSAGE TYPE::<name>TAKE OWNERSHIP ON MESSAGE TYPE::<name>ALTER ON MESSAGE TYPE::<name>Permission SyntaxCREATE DATABASE **ALTER ON DATABASE::<name>STATEMENTS: CREATE DATABASE, RESTORE DATABASE** NOTE:CREATE DATABASE is a database level permissionthat can only be granted in the master database.STATEMENTS:EXECUTE ASSTATEMENTS:EXECUTE ASSTATEMENTS:ALTER AUTHORIZATIONNotes:•ALTER AUTHORIZATION for any object might also require IMPERSONATE or membership in a role or ALTER permission on a role.•ALTER AUTHORIZATION exists at many levels in the permission model but is never inherited from ALTER AUTHORIZATION at a higher level.Note: CREATE and ALTER ASSEMBLY statements sometimes require server level EXTERNAL ACCESS ASSEMBLY and UNSAFE ASSEMBLY permissions, and can require membership in the sysadmin fixed server role.NOTES:Only members of the db_owner fixed database role can add or remove members from fixed database roles.NOTES:To add a member to a fixed server role, you must be a member of that fixed server role, or be a member of the sysadmin fixed server role.© 2014 Microsoft Corporation. All rights reserved.Database Engine PermissionsMicrosoft SQL Server 2014。
sqlcmd 使用指南
sqlcmd 使用指南英文回答:SQLCMD is a command-line tool used for interacting with Microsoft SQL Server. It allows users to execute SQL scripts, queries, and statements directly from the command prompt. In this guide, we will discuss how to use SQLCMD effectively.To start using SQLCMD, open a command prompt and navigate to the directory where SQLCMD is installed. By default, SQLCMD is located in the "C:\ProgramFiles\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn" directory. Once you are in the correct directory, you can start using SQLCMD commands.The basic syntax for using SQLCMD is as follows:sqlcmd -S server_name -U username -P password -d database_name -Q "SQL_query"Here's what each parameter means:-S: Specifies the name of the SQL Server instance you want to connect to.-U: Specifies the username to use for authentication.-P: Specifies the password for the specified username.-d: Specifies the name of the database you want to connect to.-Q: Specifies the SQL query you want to execute.For example, to connect to a SQL Server instance named "MyServer" using Windows authentication and execute a simple SELECT statement, you can use the following command:sqlcmd -S MyServer -E -d MyDatabase -Q "SELECT FROM MyTable"In this command, "-E" specifies Windows authentication, and "-d" specifies the database name.SQLCMD also supports various options and commands that can be used to customize the behavior of the tool. Some commonly used options include:-o: Specifies the output file for query results.-h: Controls the column header display.-s: Specifies the column separator character.-b: Specifies the batch size for query execution.For example, to execute a script file and save the query results to an output file, you can use the following command:sqlcmd -S MyServer -U username -P password -d MyDatabase -i script.sql -o output.txt.In this command, "-i" specifies the input script file, and "-o" specifies the output file.SQLCMD is a powerful tool for managing and interacting with SQL Server databases. It provides a convenient way to execute queries and scripts from the command prompt. By understanding the basic syntax and available options, you can leverage SQLCMD to streamline your database management tasks.中文回答:SQLCMD是一个用于与Microsoft SQL Server交互的命令行工具。
sql server存储过程判断语句
sql server存储过程判断语句SQL Server存储过程判断语句在SQL Server中,存储过程是一种预先编写的SQL语句集合,用于执行特定任务。
在存储过程中,可以使用各种条件语句来实现不同的应用场景,例如IF、CASE、WHILE等。
本文将重点介绍如何在SQL Server存储过程中使用IF语句进行条件判断。
IF语句基础在SQL Server中,IF语句可以在存储过程中实现条件判断和分支控制。
其基本语法如下所示:IF conditionBEGIN-- Statements to be executed if condition is trueENDELSEBEGIN-- Statements to be executed if condition is falseEND其中,condition是一个布尔表达式,可以使用各种比较运算符(例如=、<>、>、<等)和逻辑运算符(例如AND、OR、NOT等)。
如果condition为true,则执行IF语句块的语句;否则执行ELSE语句块的语句。
IF语句示例下面是一个简单的示例,演示了如何在SQL Server存储过程中使用IF 语句进行条件判断:CREATE PROCEDURE test_proc@num INTASBEGINIF @num > 0BEGINSELECT 'The number is positive.'ENDELSE IF @num < 0BEGINSELECT 'The number is negative.'ENDELSEBEGINSELECT 'The number is zero.'ENDEND在上面的代码中,我们创建了一个名为test_proc的存储过程,该过程接受一个@num参数,并使用IF语句进行条件判断:- 如果@num大于0,则输出“The number is positive.”。
SQL Server编码规范
文件制修订记录目录1前言 (3)1.1目的 (3)1.2术语 (3)1.3参考文献 (3)2逻辑对象的命名规范 (3)2.1数据库命名 (3)2.2数据库文件及目录 (3)2.3表 (3)2.4字段/域 (4)2.5索引 (4)2.6视图 (4)2.7存储过程 (4)2.8触发器 (4)2.9函数 (4)3可编程性编码规范 (4)3.1可编程性统一规范 (4)3.1.1外部参数 (4)3.1.2内部参数 (5)3.1.3代码编写格式规范 (5)3.2存储过程 (5)3.2.1存储过程格式: (6)3.2.2存储过程标头备注 (6)3.2.3返回值 (6)3.3函数 (6)3.3.1函数格式 (7)3.3.2函数标头备注 (7)3.4触发器 (7)3.4.1触发器格式 (7)3.4.2触发器标头备注 (8)4数据库编程技巧 (8)1前言1.1目的为了统一公司软件开发的设计过程中关于数据库SQL SEREVR设计时的命名规范和具体工作时的编程规范,便于交流和维护,特此收集、整理公司已经积累的技术资料、参考国家规范和标准、修订和编制了本编程规范。
1.2术语暂无。
1.3参考文献版本说明和修改历史2逻辑对象的命名规范2.1数据库命名数据库的命名要求使用与数据库意义相关联的拼音首字母且以“XY”打头,例如:客户资料数据库的命名可以是XYKhzl。
2.2数据库文件及目录数据库文件存放路径:d:\xydata数据库主数据文件命名:DBName_Data_XX.mdf,文件组名称:PRIMARY数据库事务日志文件命名:DBName_log_XX.ldf数据库文件组命名:主文件组 PRIMARY,次文件组 DBName_FileGroup_XX其中:DBName为数据库实际名称XX为从00开始的数字编号2.3表表的命名以业务品种为第一前缀,加下划线(_),业务模块为第二个前缀,其后紧接与表意义相关联的除系统管理库中表的命名可不用业务品种为第一前缀外,其他库中必须使用第一前缀。
SQLServer如何查看存储过程的执行计划
SQLServer如何查看存储过程的执⾏计划有时候,我们需要查看存储过程的执⾏计划,那么我们有什么⽅式获取存储过程的历史执⾏计划或当前的执⾏计划呢?下⾯总结⼀下获取存储过程的执⾏计划的⽅法。
1:我们可以通过下⾯脚本查看存储过程的执⾏计划,但是有时候,你会发现这种⽅式并不总是能够获取到存储过程的执⾏计划。
SELECTd.object_id ,DB_NAME(d.database_id) DBName ,OBJECT_NAME(object_id, database_id) 'SPName' ,d.cached_time ,st_execution_time ,d.total_elapsed_time/1000000 AS total_elapsed_time,d.total_elapsed_time / d.execution_count/1000000AS [avg_elapsed_time] ,st_elapsed_time/1000000 AS last_elapsed_time,d.execution_count ,d.total_physical_reads ,st_physical_reads ,d.total_logical_writes ,st_logical_reads ,et.text SQLText ,eqp.query_plan executionplanFROM sys.dm_exec_procedure_stats AS dCROSS APPLY sys.dm_exec_sql_text(d.sql_handle) etCROSS APPLY sys.dm_exec_query_plan(d.plan_handle) eqpWHERE OBJECT_NAME(object_id, database_id) = 'xxxx'ORDER BY [total_worker_time] DESC;有时候使⽤这种⽅式并不能获取存储过程的执⾏计划,脚本查询出来的结果,query_plan字段为NULL值,那么为什么是NULL值呢?这个是因为有⼀些限制或条件的缘故,官⽅⽂档的解释如下:Under the following conditions, no Showplan output is returned in the query_plan column of the returned table forsys.dm_exec_query_plan:·If the query plan that is specified by using plan_handle has been evicted from the plan cache, the query_plan column of the returned table is null. For example, this condition may occur if there is a time delay between when the plan handle was captured and when it was used with sys.dm_exec_query_plan.·Some Transact-SQL statements are not cached, such as bulk operation statements or statements containing string literals larger than 8 KB in size. XML Showplans for such statements cannot be retrieved by using sys.dm_exec_query_plan unless the batch is currently executing because they do not exist in the cache.·If a Transact-SQL batch or stored procedure contains a call to a user-defined function or a call to dynamic SQL, for example using EXEC (string), the compiled XML Showplan for the user-defined function is not included in the table returned bysys.dm_exec_query_plan for the batch or stored procedure. Instead, you must make a separate call to sys.dm_exec_query_plan for the plan handle that corresponds to the user-defined function.When an ad hoc query uses simple or forced parameterization, the query_plan column will contain only the statement text and not the actual query plan. To return the query plan, call sys.dm_exec_query_plan for the plan handle of the prepared parameterized query. You can determine whether the query was parameterized by referencing the sql column of the sys.syscacheobjects view or the text column of the sys.dm_exec_sql_text dynamic management view.在以下情况下,sys.dm_exec_query_plan的返回表的query_plan列为空值(query_plan列中未返回Showplan输出):·通过使⽤plan_handle查询指定的查询计划(query plan),如果plan_handle已从计划缓存中踢出(逐出),返回的表的query_plan列为null。
sqlserver数据库查询存储过程
sqlserver数据库查询存储过程英文版SQL Server Database Querying with Stored ProceduresIn the realm of database management systems, SQL Server stands tall as a reliable and powerful tool. Among its numerous features, stored procedures are a noteworthy aspect that enhances the efficiency and organization of database operations. Stored procedures are pre-compiled sets of SQL statements that can be stored in the database and called upon when needed, much like functions in programming languages.Advantages of Stored Procedures:Performance Boost: Since stored procedures are pre-compiled, they execute much faster than ad-hoc SQL queries.Code Reusability: They can be reused across multiple applications or even within the same application, reducing redundant code.Security: By limiting access to the underlying data, stored procedures provide a layer of security.Maintenance: Changes made to a stored procedure affect all its invocations, making maintenance easier.Querying with Stored Procedures in SQL Server:Querying a SQL Server database using stored procedures involves several steps:Step 1: Creating a Stored ProcedureTo create a stored procedure, you need to use the CREATE PROCEDURE statement followed by the procedure name and the SQL statements that define the procedure. For example: sqlCopy CREATE PROCEDURE GetEmployeeDetails@EmployeeID INTASBEGINSELECT * FROM Employees WHERE ID = @EmployeeIDENDCREATE PROCEDURE GetEmployeeDetails@EmployeeID INTASBEGINSELECT * FROM Employees WHERE ID = @EmployeeID ENDIn this example, GetEmployeeDetails is the name of the stored procedure, and @EmployeeID is a parameter that accepts an integer value. The SELECT statement fetches the details of an employee based on the provided EmployeeID.Step 2: Executing the Stored ProcedureTo execute the stored procedure, you use the EXEC command followed by the procedure name and any required parameters. For the above example:sqlCopy EXEC GetEmployeeDetails @EmployeeID = 1EXEC GetEmployeeDetails @EmployeeID = 1This command will execute the GetEmployeeDetails stored procedure and return the details of the employee with an ID of 1.Conclusion:Stored procedures in SQL Server are a powerful tool for organizing and optimizing database queries. They provide better performance, code reusability, and security, making them an integral part of any database-driven application. By understanding how to create and execute stored procedures, database administrators and developers can leverage the full potential of SQL Server and ensure efficient and secure data access.中文版SQL Server 数据库使用存储过程进行查询在数据库管理系统的领域中,SQL Server 作为一个可靠且强大的工具备受推崇。
t-sql 标准
t-sql 标准T-SQL(Transact-SQL)是一种面向关系数据库管理系统(RDBMS)的编程语言,主要用于Microsoft SQL Server。
下面是关于T-SQL标准的基本概念和特性的详细介绍:1. T-SQL基本概念:1.1 定义:T-SQL是Microsoft SQL Server上的一种SQL方言,它扩展了标准的SQL语言,提供了更丰富的功能,包括存储过程、触发器、视图、函数等。
1.2 特点:•过程性编程:T-SQL支持过程性编程,允许开发者创建存储过程、触发器等数据库对象。
•批量操作:提供了丰富的数据操作语句,支持批量处理,提高了效率。
•事务控制:支持事务控制,包括BEGIN TRANSACTION、COMMIT、ROLLBACK 等语句。
2. T-SQL语言特性:2.1 数据查询语言(DQL):T-SQL提供了丰富的查询语言,包括SELECT语句,用于检索数据库中的数据。
SELECT column1, column2 FROM table WHERE condition;2.2 数据操作语言(DML):T-SQL包括INSERT、UPDATE、DELETE等语句,用于对数据库中的数据进行增、删、改操作。
INSERT INTO table(column1, column2) VALUES(value1, value2);2.3 数据定义语言(DDL):T-SQL支持CREATE、ALTER、DROP等语句,用于定义数据库、表结构等。
CREATE TABLE table_name (column1 datatype, column2 datatype, ...);2.4 过程性编程:T-SQL允许创建存储过程、触发器、函数等,以实现更复杂的业务逻辑。
CREATE PROCEDURE procedure_name ASBEGIN--T-SQL statementsEND;2.5 事务控制:T-SQL提供了BEGIN TRANSACTION、COMMIT、ROLLBACK等语句,用于控制事务的开始、提交和回滚。
SQLServer运行状况监控SQL语句
SQLServer运⾏状况监控SQL语句Microsoft SQL Server 2005 提供了⼀些⼯具来监控数据库。
⽅法之⼀是动态管理视图。
动态管理视图 (DMV) 和动态管理函数 (DMF) 返回的服务器状态信息可⽤于监控服务器实例的运⾏状况、诊断问题和优化性能。
常规服务器动态管理对象包括:dm_db_*:数据库和数据库对象dm_exec_*:执⾏⽤户代码和关联的连接dm_os_*:内存、锁定和时间安排dm_tran_*:事务和隔离dm_io_*:⽹络和磁盘的输⼊/输出此部分介绍为监控 SQL Server 运⾏状况⽽针对这些动态管理视图和函数运⾏的⼀些常⽤查询。
您可以运⾏以下查询来获取所有 DMV 和 DMF 名称:SELECT*FROM sys.system_objectsWHERE name LIKE'dm_%'ORDER BY name监控 CPUCPU 瓶颈通常由以下原因引起:查询计划并⾮最优、配置不当、设计因素不良或硬件资源不⾜。
下⾯的常⽤查询可帮助您确定导致 CPU 瓶颈的原因。
下⾯的查询使您能够深⼊了解当前缓存的哪些批处理或过程占⽤了⼤部分 CPU 资源。
SELECT TOP50SUM(qs.total_worker_time) AS total_cpu_time,SUM(qs.execution_count) AS total_execution_count,COUNT(*) AS number_of_statements,qs.sql_handleFROM sys.dm_exec_query_stats AS qsGROUP BY qs.sql_handleORDER BY SUM(qs.total_worker_time) DESC下⾯的查询显⽰缓存计划所占⽤的 CPU 总使⽤率(带 SQL ⽂本)。
SELECTtotal_cpu_time,total_execution_count,number_of_statements,s2.text--(SELECT SUBSTRING(s2.text, statement_start_offset / 2, ((CASE WHEN statement_end_offset = -1 THEN (LEN(CONVERT(NVARCHAR(MAX), s2.text)) * 2) ELSE statement_end_offset END) - statement_start_offset) / 2) ) AS query_te FROM(SELECT TOP50SUM(qs.total_worker_time) AS total_cpu_time,SUM(qs.execution_count) AS total_execution_count,COUNT(*) AS number_of_statements,qs.sql_handle --,--MIN(statement_start_offset) AS statement_start_offset,--MAX(statement_end_offset) AS statement_end_offsetFROMsys.dm_exec_query_stats AS qsGROUP BY qs.sql_handleORDER BY SUM(qs.total_worker_time) DESC) AS statsCROSS APPLY sys.dm_exec_sql_text(stats.sql_handle) AS s2下⾯的查询显⽰ CPU 平均占⽤率最⾼的前 50 个 SQL 语句。
sql server创建存储过程的语句
SQL Server中创建存储过程的语句存储过程是一组SQL语句的集合,可以被SQL Server编译和存储。
通过存储过程,可以将经常使用的代码存储在一个地方,以便在需要的时候进行调用。
存储过程可以提高数据库性能,简化复杂的操作,并且能够加强数据库安全性。
下面是在SQL Server中创建存储过程的语句,以及一些创建存储过程时需要注意的事项。
1. 创建简单的存储过程要创建一个简单的存储过程,可以使用以下语法:```sqlCREATE PROCEDURE procedure_nameASSQL_statements```其中,procedure_name是存储过程的名称,SQL_statements是存储过程包含的SQL语句。
创建存储过程的时候,需要确保存储过程的名称没有被其他对象使用,并且要遵循SQL Server对象命名规范。
2. 创建带参数的存储过程如果需要在存储过程中使用参数,可以在CREATE PROCEDURE语句中指定参数的名称和数据类型。
例如:```sqlCREATE PROCEDURE procedure_nameparameter1 datatype,parameter2 datatypeASSQL_statements```在存储过程中使用参数时,可以通过在SQL_statements中使用parameter_name的方式来引用参数。
3. 创建带返回值的存储过程有时候需要在存储过程中返回一个值,可以使用OUTPUT参数。
例如:```sqlCREATE PROCEDURE procedure_nameparameter1 datatype,parameter2 datatype,return_value datatype OUTPUTASSET return_value = some_calculation```在这个例子中,return_value是一个输出参数,存储过程执行完毕后,return_value的值将被传递出去。
sp
一、前言:在经过一段时间的存储过程开发之后,写下了一些开发时候的小结和经验与大家共享,希望对大家有益,主要是针对Sybase和SQL Server数据库,但其它数据库应该有一些共性。
二、适合读者对象:数据库开发程序员,数据库的数据量很多,涉及到对SP(存储过程)的优化的项目开发人员,对数据库有浓厚兴趣的人。
三、介绍:在数据库的开发过程中,经常会遇到复杂的业务逻辑和对数据库的操作,这个时候就会用SP来封装数据库操作。
如果项目的SP较多,书写又没有一定的规范,将会影响以后的系统维护困难和大SP逻辑的难以理解,另外如果数据库的数据量大或者项目对SP的性能要求很,就会遇到优化的问题,否则速度有可能很慢,经过亲身经验,一个经过优化过的SP要比一个性能差的SP的效率甚至高几百倍。
四、内容:1、开发人员如果用到其他库的Table或View,务必在当前库中建立View来实现跨库操作,最好不要直接使用“databse.dbo.table_name”,因为sp_depends不能显示出该SP所使用的跨库table或view,不方便校验。
2、开发人员在提交SP前,必须已经使用set showplan on分析过查询计划,做过自身的查询优化检查。
3、高程序运行效率,优化应用程序,在SP编写过程中应该注意以下几点:a)SQL的使用规范:i.尽量避免大事务操作,慎用holdlock子句,提高系统并发能力。
ii.尽量避免反复访问同一张或几张表,尤其是数据量较大的表,可以考虑先根据条件提取数据到临时表中,然后再做连接。
iii.尽量避免使用游标,因为游标的效率较差,如果游标操作的数据超过1万行,那么就应该改写;如果使用了游标,就要尽量避免在游标循环中再进行表连接的操作。
iv.注意where字句写法,必须考虑语句顺序,应该根据索引顺序、范围大小来确定条件子句的前后顺序,尽可能的让字段顺序与索引顺序相一致,范围从大到小。
v.不要在where子句中的“=”左边进行函数、算术运算或其他表达式运算,否则系统将可能无法正确使用索引。
sql数据库导入导出(ImportandexportSQLdatabase)
sql数据库导入导出(Import and export SQL database)Data conversion between SQL SERVER and ACCESS and EXCELFamiliar with SQL SERVER 2000 database administrators know that their DTS can import and export data, in fact, we can also use Transact-SQL statements for import and export operations. In the Transact-SQL statement, we mainly use the OpenDataSource function, the OPENROWSET function, and the function details, and refer to the SQL online help. Using the following methods, SQL, SERVER, ACCESS, and EXCEL data conversion can be easily implemented, as explained below:First, import and export data of SQL, SERVER and ACCESS Routine data import and export:Use the DTS wizard to migrate your Access data to SQL Server, and you can use these steps:1 on the Tools (tools) menu in the SQL SERVER enterprise manager, select Data Transformation2Services (data conversion service), and then select czdImport Data (import data).3 in the Choose a Data Source (select the data source) dialog box, select Microsoft Access as the Source, and then type the name of your.Mdb database (.Mdb file extension) or browse to find the file.4 in the Choose a Destination (select the target) dialog box,select Microsoft OLE DB Prov ider for SQL Server, select the database server, and then click the necessary validation methods.5 in the Specify Table Copy (specify the table copy) or the Query (query) dialog box, click Copy tables (copy table).6 in the Select Source Tables (select the source table) dialog box, click Select All (all selected). Next, complete.The Transact-SQL statement is imported and exported:1. query access data in SQL SERVER:- ======================================================SELECT *FROM OpenDataSource ('Microsoft.Jet.OLEDB.4.0','Data Source=, "c:\DB.mdb"; User ID=Admin; Password=')... Table name-------------------------------------------------------------------------------------------------2. import access into SQL server- ======================================================Run in SQL SERVER:SELECT *INTO newtableFROM OPENDATASOURCE ('Microsoft.Jet.OLEDB.4.0','Data Source=, "c:\DB.mdb"; User ID=Admin; Password=')... Table name-------------------------------------------------------------------------------------------------3. insert data from the SQL SERVER table into the Access table- ======================================================Run in SQL SERVER:Insert into OpenDataSource ('Microsoft.Jet.OLEDB.4.0','Data Source=, "c:\DB.mdb"; User ID=Admin; Password=')... Table name(column 1, column 2)Select column 1, column 2, from, SQL tableExample:Insert into OPENROWSET ('Microsoft.Jet.OLEDB.4.0','C:\db.mdb';'admin'; '', 'Test')Select, ID, name, from, TestINSERT, INTO, OPENROWSET('Microsoft.Jet.OLEDB.4.0','c:\trade.mdb','admin';', ', table name)SELECT *FROM sqltablename-------------------------------------------------------------------------------------------------2。
SQLSERVER存储过程及调用详解
SQLSERVER存储过程及调用详解SQL Server存储过程是一组预编译的SQL语句和控制语句的集合,它们作为一个单独的单元存储在数据库中。
存储过程可以通过调用来执行,它们具有以下优点:提高性能、增加安全性、提高代码复用和可维护性。
本文将详细解释SQL Server存储过程的创建和调用。
首先,我们需要了解如何创建一个SQL Server存储过程。
创建存储过程的语法如下:```CREATE PROCEDURE procedure_nameASsql_statements```- `procedure_name`是存储过程的名称。
- `sql_statements`是存储过程的主体,包含要执行的SQL语句和控制语句。
下面是一个示例,演示如何创建一个存储过程,该存储过程接受一个输入参数并返回一个结果:```CREATE PROCEDURE GetCustomerCountASBEGINSELECT COUNT(*) AS TotalCustomersFROM CustomersEND```在上面的示例中,我们创建了一个名为`GetCustomerCount`的存储过程,该存储过程接受一个城市名称作为输入参数。
它执行一个`SELECT`语句来计算特定城市的客户数量,并将结果返回。
要调用存储过程,可以使用`EXECUTE`或`EXEC`关键字,后跟存储过程的名称和参数值(如果有的话)。
下面是一个示例,演示如何调用上面创建的存储过程:```EXECUTE GetCustomerCount 'London'```上述代码将执行`GetCustomerCount`存储过程,并将`'London'`作为参数传递。
存储过程将返回结果集,其中包含伦敦的客户数量。
如果存储过程具有输出参数,可以使用`OUTPUT`关键字将其指定为输出参数。
下面是一个示例,演示如何在存储过程中使用输出参数:```CREATE PROCEDURE GetCustomerCountASBEGINFROM CustomersEND`````````除了输入参数和输出参数,存储过程还可以有返回值。
几个小型数据库的比较
几个小型数据库的比较Access,MSDE 2000,Embedded Firebird,SQLite等都是可以免费再分发(free redistributable)的数据库。
相比而言,MSDE 2000 显著缺点是需要安装,最大优点是和服务器端的SQL Server 编程模型一致,开发便利。
Access的显著缺点是功能较少,不支持事务等常用功能,最大优点是简单、多数开发者都很熟悉,部署也很方便。
SQLite支持事务,也是一款单文件数据库,比较不足的是 .NET Data Provider 还不是很成熟。
Firebird则同时具有:单文件、部署简单不需安装(只需XCOPY 两个文件)、支持事务、存储过程、触发器,.NET Data Provider比较稳定成熟等优点。
这个星球上的数据库实在不胜枚举,这里只列一些我接触过的常见的。
可以稍微夸张点说,有交互的应用,起码得用一下数据保存,即便是自定义结构的数据保存,还是最常见的INI、XML等,都可以算是“数据库”,真正点的,如DBase系列、FoxBase、FoxPro、MSAccess、InterBase、MS SQL Server、Oracle、DB2等,这些是商业化的数据库,前面几个只能算是数据库,后面几个是RMDBS(关系型数据库管理系统)。
对应商业化的,有开源的:SQLite、SimpleSQL、Berkely DB、Minosse、Firebird( 前身是是Borland公司的InterBase)、PostgreSQL、MySQL 等。
□SQLite:大家可以看我的SQLite系列随笔,C编写的,可以跨操作平台,支持大部分ANSI SQL 92,它是嵌入式的轻量级关系形数据库引擎,只需要一个DLL,体积为250k,数据库也只是一个文件,零配置,便可工作。
既然开源,你甚至可以把它嵌入你的程序中。
核心开发人员只有一个,最近加入了另外一个,也就是2个人而已,实在佩服,目前发展到3.1.0,相当高效稳定,有开源驱动在上有其 Data Provider for SQLite :https:///projects/adodotnetsqlite/。
sql server ddl语法
sql server ddl语法一、DDL语法简介DDL(Data Definition Language)是指数据库定义语言,用于定义和管理数据库中的对象。
SQL Server DDL语法是指SQL Server数据库定义语言的语法规则集合,主要包括创建、修改和删除数据库对象的语句。
二、创建表创建表是SQL Server DDL语法中最常用的操作之一。
以下是创建表的基本语法:```CREATE TABLE table_name (column1 datatype [ NULL | NOT NULL ],column2 datatype [ NULL | NOT NULL ],...);```其中,table_name为要创建的表名;column1、column2等为列名;datatype为数据类型;NULL表示该列可以为空;NOT NULL表示该列不能为空。
三、修改表在实际应用中,我们经常需要对已有的表进行修改。
以下是SQL Server DDL语法中常用的修改表操作:1. 添加新列```ALTER TABLE table_nameADD column_name datatype [ NULL | NOT NULL ];```2. 修改列数据类型```ALTER TABLE table_nameALTER COLUMN column_name datatype;```3. 修改列名称```EXEC sp_rename 'table_name.old_column_name','new_column_name', 'COLUMN';```四、删除表删除表是SQL Server DDL语法中常用的操作之一。
以下是删除表的基本语法:```DROP TABLE table_name;```其中,table_name为要删除的表名。
五、创建索引索引可以提高查询效率,因此在实际应用中非常重要。
sql server for 用法
sql server for 用法SQL Server是一种关系型数据库管理系统(RDBMS),由Microsoft开发和发布。
它是一种功能强大的数据库管理软件,用于存储和管理大量结构化数据,并提供高性能、高可靠性和安全性。
以下是SQL Server的一些常见用法:1. 数据存储和管理:SQL Server用于创建、管理和维护关系型数据库。
您可以使用SQL语言(如T-SQL)来创建表、插入、更新和删除数据,以及执行各种数据库操作。
2. 数据查询和分析:SQL Server支持高效的数据查询和分析功能。
您可以使用SQL语句来检索和分析数据库中的数据,并使用聚合函数、排序和过滤条件来获取特定的结果。
3. 数据备份和恢复:SQL Server提供了强大的数据备份和恢复功能,可用于保护数据库免受数据丢失或损坏。
您可以设置定期备份数据库,并在需要时使用备份文件进行恢复。
4. 安全性管理:SQL Server提供了多种安全性功能,可以管理数据库的访问权限、加密数据、监视和审计数据库活动,以及应对潜在的安全威胁。
5. 数据复制和同步:SQL Server支持数据复制和同步功能,可以将数据从一个数据库复制到另一个数据库,并确保数据的一致性和准确性。
6. 高可用性和灾难恢复:SQL Server提供了高可用性和灾难恢复功能,如故障转移集群、数据库镜像和日志传送。
这些功能确保数据库的连续性和可靠性,即使在出现硬件故障或其他灾难情况下也能迅速恢复。
以上仅是SQL Server的一些常见用法,它还提供了许多其他功能和工具,如数据仓库、报表生成、数据分析服务等。
使用SQL Server,您可以构建和管理强大的数据库应用程序,并有效地处理大量数据。
sql server中if函数嵌套
sql server中if函数嵌套在SQL Server中,IF函数可以用来根据特定条件执行不同的操作。
IF函数嵌套是指在IF函数的条件分支中再次使用IF函数。
本文将介绍SQL Server中IF函数嵌套的使用方法和注意事项。
IF函数是一种控制流程函数,它允许我们根据条件来选择执行不同的代码块。
在SQL Server中,IF函数的语法如下:```IF condition{ statements }[ ELSE{ statements } ]```其中,`condition`是一个布尔表达式,当这个表达式的值为真时,执行`{ statements }`中的代码块;否则,执行可选的`ELSE{ statements }`中的代码块。
在某些情况下,一个简单的IF函数是不够的,我们可能需要根据多个条件来选择执行不同的代码块。
这时,我们可以使用IF函数的嵌套来实现这一需求。
IF函数的嵌套可以通过在IF函数的代码块内部再次使用IF函数来实现。
例如,我们可以这样嵌套使用IF函数:```IF condition1{IF condition2{ statements }ELSE{ statements }}ELSE{ statements }```在这个例子中,如果`condition1`为真,则首先判断`condition2`的值,如果为真,则执行第一个`{ statements }`中的代码块,否则执行第二个`{ statements }`中的代码块。
如果`condition1`为假,则直接执行外层的`{ statements }`代码块。
需要注意的是,IF函数的嵌套可以多次进行,我们可以根据实际需求嵌套多个IF函数。
在使用IF函数的嵌套时,需要注意以下几点:1. 可以对条件表达式进行逻辑运算,例如使用AND、OR等操作符来组合多个条件。
2. IF函数的嵌套可以帮助我们实现更复杂的控制流程,但也增加了代码的复杂性。
sqlsever 条件判断取值
sqlsever 条件判断取值英文回答:In SQL Server, conditional statements allow you to execute different actions based on the evaluation of a specified condition. The most commonly used conditional statement is the IF-ELSE statement, which takes the following form:IF (condition)。
BEGIN.-Code to be executed if the condition is true.END.ELSE.BEGIN.-Code to be executed if the condition is false.END.For example, the following statement checks if thevalue of the column "Age" is greater than 18:IF (Age > 18)。
BEGIN.-Code to be executed if the age is greater than 18。
END.ELSE.BEGIN.-Code to be executed if the age is 18 or less.END.In addition to the IF-ELSE statement, SQL Server also supports the CASE statement, which allows for more complex conditional evaluations. The CASE statement takes the following form:CASE.WHEN (condition1) THEN result1。
isql实用工具(ISQLutility)
isql 实用工具(ISQL utility)ISQL utilityThe ISQL utility ISQL utility enables you to input Transact-SQL statements, system processes, and script files; and usesDB-Library to communicate with Microsoft SQL Server "2000".Syntax ISQLLists the servers configured locally and the name of the server that broadcasts on the network.-U login_idUser login ID. Login ID case sensitive.-P passwordIs the user specified password. If you don't use the -P option, ISQL prompts you to enter the password. If you use the -P option without the password at the end of the command prompt, the ISQL uses the default password (NULL). Password case sensitive.The ISQLPASSWORD environment variable allows you to set the default password for the current session. Therefore, no hard code is required to set the password in the batch file.If you do not specify a password for the -P option, ISQL first checks the ISQLPASSWORD variable. If no value is set, ISQL uses the default password (NULL). The following example sets the ISQLPASSWORD variable at the command prompt, and then accessesthe ISQL utility:C:\>SET ISQLPASSWORD=abracadabraC:\>isql-EUse trusted connections instead of requesting passwords.-S server_nameSpecifies the default instance of the SQL Server to connect to. ISQL does not support linking to SQL Server 2000 named instances. If no server is specified, ISQL will connect to the default instance of the SQL Server on the local computer. This option is required if you want to execute ISQL from a remote computer on the network.-H wksta_nameWorkstation name. The workstation name is stored in sysprocesses.hostname and displayed by sp_who. If not specified, the current computer name is used.-d db_nameIssue a USE db_name statement when starting isql.-l time_outThe number of seconds before the ISQL logon timeout is specified. If the time_out value is not specified, the command is runindefinitely. The default timeout to logon to ISQL is 8 seconds.-t time_outThe number of seconds before the specified command timeout. If the time_out value is not specified, the command will run indefinitely; the default timeout to log in to ISQL is 8 seconds.-h headersSpecifies the number of rows to be printed between column headings. The default is to print a title for each query result set. Use - 1 specifies not to print titles. If you use - 1, there is no space between parameters and settings (-h-1, not -h –1).-s col_separatorSpecify column separatorCharacter, its default is blank. If you want to use a special meaning to the operating system (such as the character |; & < >), please have the characters in double quotes (") quoted.-w column_widthAllows users to set the width of screen output. The default is 80 characters. When the output line reaches its maximum screen width, it splits into multiple rows.-a packet_sizeEnables you to request packets of different sizes. The effective value of packet_size is between 512 and 65535. The default value of ISQL in Microsoft Windows NT version is 8192; in addition, the default value of ISQL in Microsoft MS-DOS version is 512, but in this version you can request larger data packets. The increase of packet size can improve the performance of larger script execution. In this execution, the number of SQL statements between GO commands is very important. The test of Microsoft shows that 8192 is the typical fastest setting of bulk copy operation. A larger packet size can be requested, but if the request cannot be approved, the ISQL defaults to 512.-eReturn input.-x max_text_sizeSpecifies the maximum length of return text data, in bytes. Text values longer than max_text_size will be truncated.If no max_text_size is specified, the text data is truncated at 4096 bytes.-c cmd_endSpecifies the command terminator. By default, the is terminated by sending GO in a single line and sent to SQL Server 2000. Whenresetting the command terminator, do not use the Transact-SQL reserved word or character that has special meaning to the operating system, whether or not it has a backslash.-q "query""When ISQL is started, the query is executed, but the ISQL is not exited when the query is completed. (note that query statements should not contain GO). If you send a query from a batch file, you can use%variables. The environment%variables% is also available. For example:SET table = sysobjectsisql /q "Select * from%table%""The query is enclosed in double quotation marks, and any content embedded in the query is enclosed in single quotation marks.-Q "query""Execute query and exit ISQL immediately when the query completes. The query is enclosed in double quotation marks, and any content embedded in the query is enclosed in single quotation marks.-nDelete numbering and prompt symbols from the input line (>).-m error_levelDisplay of custom error information. Displays the number,status, and error level of the specified or higher severity level errors. Any information that does not display a severity level below the specified level. -1 specifies that all headers are returned with the message, even the message of the information class. If you use - 1, there is no space between parameters and settings (-m-1, not -m -1).-r {0 1} |Redirect the message output to the screen (stderr). If the parameter is not specified, or the specified parameter is 0, then the only directional severity level of 17 or higher error information. If the specified parameter is 1, all message output (including "print") will be redirected.-i input_fileIdentifies a file that contains a batch of SQL statements or stored procedures. Less than (<) comparison operators can be used instead of - I.-o output_fileIdentifies files that receive output from the isql. Larger than (>) comparison operators can be used instead of - O.-pPrint performance statistics.-bWhen the specified error occurs, ISQL exits and returns a DOS ERRORLEVEL value. When the severity level of SQL Server error information is 10 or higher, the value returned to the DOS ERRORLEVEL variable is 1; otherwise, the return value is 0. The MS-DOS batch file can test the value of DOS ERRORLEVEL and handle errors appropriately.-OThe behavior of specifying ISQL to revert to earlier versions. The following functions are disabled:EOF batch processingAutomatic adjustment of console widthWide informationThis option also sets the default value of DOS ERRORLEVEL to - 1.NotesAll DB-Library applications (such as ISQL) connect to SQL Server 2000 and work as a SQL Server 6.5 level client. They do not support some of the functions of SQL Server 2000. The OSQL utility is based on ODBC and supports all the functions of SQL Server 2000. Using OSQL to run scripts that ISQL cannot run. For more information on the SQL Server 6.5 level client limit, see the early version client connection to SQL Server 2000 inthe SQL Server online book.By default, the SQL query analyzer saves the SQL script as a Unicode file. The ISQL utility does not support the Unicode input file. Attempting to specify one of these files in the -i switch causes error 170:Incorrect syntax near ''Run these Unicode files using the OSQL utility. Another method is to specify ANSI instead of Unicode in the file format list of the file / Save As dialog box in the SQL query analyzer.Like most DB-Library applications, the ISQL utility does not set any connection options by default. If a user wishes to use a specific connection option setting, the SET statement must be sent interactively or in a script.The ISQL utility starts directly from the operating system and uses the case - sensitive options listed in this article. After startup, ISQL accepts the Transact-SQL statement and sends them interactively to SQL Server 2000. The result will be formatted and printed to the standard output device (screen). You can exit ISQL using QUIT or EXIT.If the username is not specified when the ISQL is started, SQL Server 2000 checks the environment variables and uses them, such as isqluser= (user) or isqlserver= (server). If the environment variable is not set, the workstation user name is used. If the server is not specified, the workstation name is used.If -U or -P options are not used, SQL Server 2000 tries to connect with Windows authentication mode. Authentication is based on the user's Windows NT account running isql.In addition to the Transact-SQL statements used in ISQL, the commands in the following table are also available.Command descriptionAll statements entered after the last GO command is executed by GO.RESET clears all the input statements.ED call editor.!! Command executes the operating system commands.QUIT or EXIT () exits isql.CTRL+C does not exit ISQL and ends queries.Only if the command terminator GO (default), RESET, ED,..., EXIT, QUIT and CTRL+C appear at the beginning of a line (followed by the ISQL prompt) can they be identified. ISQL ignores any input after these keywords in the same row.GO indicates the end of a batch and the execution of any cached Transact-SQL statement. At the end of each input line, press the ENTER key, and ISQL will cache the statement of the row.When you type GO and press the ENTER key, all current cached statements will be sent to SQL Server 2000 as a batch.The current ISQL utility works as if there were implicit GO at the end of any executed script, so all the statements in the script would be executed. Some of the earlier versions of ISQL will not send any statements to the server unless there is at least one GO in the output script. None of the statements after the last GO is executed.End the command by entering the line with the command terminator as the start line. You can enter an integer after the command terminator to specify the number of times the command is run. For example, if you want to execute this command 100 times, type in:SELECT x = 1GO 100The results are printed at the end of execution. When using ISQL, the number of characters per line is limited to 1000. Long statements should be written across multiple lines.Through at the beginning of the type ED, the user can call in the buffer on the current query editor. The editor is defined in the EDITOR environment variable. The default editor is "Edit" for MS-DOS and Windows NT". You can specify other editors by setting EDITOR environment variables. For example, if you want to specify the default editor as Notepad, enter at the operating system prompt:SET EDITOR=notepadFor more information about where to find or run this utility, see the command prompt utilities.The operating system command starts a row with two exclamation marks, and then enters the command, and also executes the operating system commands. The DOSKEY command revocation tool can be used to retract and modify the ISQL statements previously entered on the computer running Windows NT. Typing RESET clears existing query buffers.When running stored procedures,ISQL prints a blank line between each result set in batch processing. In addition, if the statement has not been applied, the "0 rows affected" message will not appear.Interactive use of ISQL. If you want to interact with ISQL, type the ISQL command (and any options) at the command prompt.You can read from a file that contains a query executed by ISQL (such as Stores.qry) by typing a descending command:ISQL /U Alma /P /i stores.qryThe file must contain a command terminator.You can read in a file that contains a query, such as Titles.qry, by typing a descending command and directing the result to another file:ISQL /U Alma /P /i titles.qry /o titles.resInteractive use of ISQL, in order to read the operating system files into the command buffer, you can use: R file_name. Do not include the command terminator in the file; after the completion of the edit, the interactive input terminator.Insert annotations can be included in the Transact-SQL statement submitted to SQL Server 2000 by isql. Allow the use of two kinds of types: comment style -- and / * * /...For more information, see the use of annotations.Using EXIT to return ISQL results, you can use the result of the SELECT statement as the return value of isql. The first column of the first result line is converted to an integer of 4 bytes (long integer). MS-DOS transfers low byte to parent process or operating system error level. Windows NT passes the entire 4 byte integer. Grammar as:EXIT (query)For example:EXIT (SELECT @@rowcount)EXIT (SELECT 5)You can also include the EXIT parameter as part of the batch file. For example:ISQL /Q "EXIT" (SELECT COUNT (*) FROM'%1')"The ISQL utility passes all the input from parentheses () to the server. EXIT () statements can span lines. If the stored system procedure selects a collection and returns a value, only the selected content is returned. The EXIT () statement with no arguments between parentheses performs all the contents before this statement in the batch, and then exits without returning the value.There are four kinds of EXIT format:EXIT does not perform batch processing and exits immediately without return value.EXIT () quit after executing batch, no return value.EXIT (query) executes batch processing including queries, returns the result of the query, and then exits.RAISERROR with a state of 127. If RAISERROR is used in the ISQL script and the state 127 appears, ISQL will exit and return the message ID to the client program. For example:RAISERROR (50001, 10, 127)The error will cause the ISQL script to terminate and return the message ID 50001 to the client program.SQL Server retains the return value from -1 to -99; ISQL defines the following values:-100 encountered errors before selecting a return value. -101 cannot find rows when the return value is selected. Conversion error when -102 returns a value.。
sqlserver if语句
sqlserver if语句SQL Server是一款关系型数据库管理系统,它支持许多编程语言。
在SQL Server中,IF语句被用来实现条件控制流程。
本文将逐步介绍如何使用SQL Server中的IF语句。
第一步:IF语句的语法在SQL Server中,IF语句的语法如下:IF BOOLEAN_EXPRESSIONBEGINSQL STATEMENTSEND其中,BOOLEAN_EXPRESSION是用于评估条件的表达式。
如果BOOLEAN_EXPRESSION的值为TRUE,则执行SQL STATEMENTS中的代码块。
如果BOOLEAN_EXPRESSION的值为FALSE,则跳过SQL STATEMENTS中的代码块,继续执行后续代码。
可以看出,IF语句的执行结果有两种:执行或跳过。
第二步:IF语句的使用下面的例子演示了如何使用IF语句:IF (SELECT COUNT(*) FROM Employee) > 0BEGINSELECT * FROM EmployeeEND在这个例子中,使用SELECT COUNT(*) FROM Employee表达式计算Employee表中的数据行数。
如果结果大于0,则执行SELECT * FROM Employee代码块,否则跳过该代码。
第三步:IF ELSE语句IF ELSE语句用于选择两个代码块中的一个进行执行。
当BOOLEAN_EXPRESSION的值为TRUE时,执行IF块中所有的SQL语句。
当BOOLEAN_EXPRESSION的值为FALSE时,执行ELSE块中的SQL语句。
下面是IF ELSE语句的基本语法:IF BOOLEAN_EXPRESSIONBEGINSQL STATEMENTSENDELSEBEGINSQL STATEMENTSEND下面的例子演示了如何使用IF ELSE语句:IF (SELECT Salary FROM Employee WHERE EmployeeID = 1) > 1000BEGINPRINT 'The salary is greater than 1000'ENDELSEBEGINPRINT 'The salary is less than or equal to 1000'END在这个例子中,查询Employee表中EmployeeID=1的员工的薪水。
sql parameters的用法
在SQL中,参数(Parameters)是用来传递值到SQL 查询或存储过程中的占位符。
使用参数可以带来多个好处,包括预防SQL 注入攻击、提高查询性能以及使代码更加清晰和易维护。
下面是一些关于SQL 参数的用法,具体语法可能因数据库系统而异:1. 预备语句(Prepared Statements):使用预备语句可以防止SQL 注入攻击,并提高执行相似SQL 语句的性能。
具体的语法可能因数据库而异。
在Java中使用JDBC 预备语句:// 示例使用Java 的JDBCString sql = "SELECT * FROM users WHERE username = ?";try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { preparedStatement.setString(1, "john_doe"); // 设置参数值ResultSet resultSet = preparedStatement.executeQuery();// 处理结果集}2. 存储过程中的参数:在存储过程中,参数用于接收输入值或返回输出值。
具体的语法也可能因数据库而异。
在SQL Server中定义存储过程带有参数:CREATE PROCEDURE GetUserInfo@UserName NV ARCHAR(50)ASBEGINSELECT * FROM Users WHERE UserName = @UserNameEND在Java中调用SQL Server 存储过程:try (CallableStatement cstmt = connection.prepareCall("{call GetUserInfo(?)}")) {cstmt.setString(1, "john_doe"); // 设置参数值ResultSet resultSet = cstmt.executeQuery();// 处理结果集}3. IN 和OUT 参数:一些数据库允许定义IN(输入)和OUT(输出)参数,以便在调用存储过程时传递和接收值。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
The Language of SQLSQL Statements and Data for SQL ServerHow to Use This DocumentThis document contains all the SQL statements in "The Language of SQL" in the syntax of Microsoft SQL Server.Additionally, this document allows you to create the same data used in the book. This will allow you to execute the SQL statements and see the same results.There are three prerequisites:∙Install SQL Server Express 2008∙Install SQL Server Management Studio∙Create a databaseAppendix A of "The Language of SQL" contains instructions on how do these installs and create a database.To use any of the SQL statements in this document, simply copy the desired statements into SQL Management Studio.For each chapter in this book, you will find two sets of SQL statements:∙Setup ScriptsThe setup scripts allow you to create the data needed to execute all statements in thatchapter. These scripts consist of CREATE TABLE commands to create the tables andINSERT statements to insert data into those tables. There are also DROP TABLEstatements which delete the tables if that table already exists. Note that you will see a GO command after each DROP TABLE statement. The GO serves the purpose of forcing the DROP TABLE to execute prior to the subsequent CREATE TABLE.∙SQL Statements from the BookEach statement in the book is shown in the correct syntax for Microsoft SQL Server. If aparticular statement doesn't apply to SQL Server, then it isn't shown.Each setup script applies only to the SQL statements which immediately follow. For example, the statements shown for chapter 4 consist of a setup script, followed by the SQL statements found in that chapter. You don't need to execute the chapter 2 or 3 setup scripts in order to use the scripts in chapter 4.The setup scripts in chapters 2, 6, 17, and 18 have been separated into multiple parts. This occurs because those chapters have situations where data is modified in some way, requiring additional setup scripts for subsequent SQL statments to work correctly.All of the statements in a setup script can be executed all at once. However, if you should encounter any problems in executing a setup script, try executing the statements one at a time. In most cases, that will solve any problems you encounter.There are no scripts or SQL statements for chapters 1, 19 or 20.The following is a list of chapters. Click on any of these links to go immediately to the SQL for that chapter.Chapter 2Chapter 3Chapter 4Chapter 5Chapter 6Chapter 7Chapter 8Chapter 9Chapter 10Chapter 11Chapter 12Chapter 13Chapter 14Chapter 15Chapter 16Chapter 17Chapter 18Chapter 2Setup Script - Part 1:IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Customers')AND TYPE IN (N'U'))DROP TABLE CustomersGOCREATE TABLE Customers(CustomerID INT NOT NULL,FirstName VARCHAR(45) NULL,Lastname VARCHAR(45) NULL)INSERT INTO Customers(CustomerID, FirstName, Lastname) VALUES (1, 'William', 'Smith')INSERT INTO Customers(CustomerID, FirstName, Lastname) VALUES (2, 'Natalie', 'Lopez')INSERT INTO Customers(CustomerID, FirstName, Lastname) VALUES (3, 'Brenda', 'Harper')Statements from Book:SELECT * FROM CustomersSELECT *FROM CustomersSELECT LastNameFROM CustomersSELECTFirstName,LastNameFROM CustomersSetup Script - Part 2:IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Customers')AND TYPE IN (N'U'))DROP TABLE CustomersGOCREATE TABLE Customers([Last Name] VARCHAR(45) NULL)INSERT INTO Customers ([Last Name]) VALUES ('Smith') INSERT INTO Customers ([Last Name]) VALUES ('Lopez') INSERT INTO Customers ([Last Name]) VALUES ('Harper') Statements from Book:SELECT[Last Name]FROM CustomersChapter 3Setup Script:IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Orders')AND TYPE IN (N'U'))DROP TABLE OrdersGOCREATE TABLE Orders(OrderID INT NOT NULL,FirstName VARCHAR(45) NULL,Lastname VARCHAR(45) NULL,QuantityPurchased INT NULL,PricePerItem FLOAT NULL)INSERT INTO Orders(OrderID, FirstName, Lastname, QuantityPurchased, PricePerItem) VALUES (1, 'William', 'Smith', 4, 2.5)INSERT INTO Orders(OrderID, FirstName, Lastname, QuantityPurchased, PricePerItem) VALUES (2, 'Natalie', 'Lopez', 10, 1.25)INSERT INTO Orders(OrderID, FirstName, Lastname, QuantityPurchased, PricePerItem) VALUES (3, 'Brenda', 'Harper', 5, 4)IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Orders123')AND TYPE IN (N'U'))DROP TABLE Orders123GOCREATE TABLE Orders123(LastName VARCHAR(45) NOT NULL)INSERT INTO Orders123 (Lastname)VALUES ('Smith')Statements from Book:SELECT'First Name: ',FirstNameFROM OrdersSELECT5,FirstNameFROM OrdersSELECTOrderID,QuantityPurchased,PricePerItem,QuantityPurchased * PricePerItem FROM OrdersSELECTOrderID,FirstName,LastName,FirstName + ' ' + LastNameFROM OrdersSELECTOrderID,FirstName,LastName,FirstName + ' ' + LastName AS 'Name' FROM OrdersSELECTLastNameFROM Orders123 AS Orders SELECTstNameFROM Orders123 AS OrdersChapter 4Setup Script:IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'table1')AND TYPE IN (N'U'))DROP TABLE table1GOCREATE TABLE table1(President VARCHAR(20) NULL)INSERT INTO table1 (President)VALUES ('George Washington ')IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Orders')AND TYPE IN (N'U'))DROP TABLE OrdersGOCREATE TABLE Orders(OrderID INT NOT NULL,FirstName VARCHAR(45) NULL,LastName VARCHAR(45) NULL,QuantityPurchased INT NULL,PricePerItem FLOAT NULL)INSERT INTO Orders (OrderID, FirstName, LastName, QuantityPurchased, PricePerItem) VALUES (1, 'William', 'Smith', 4, 2.5)INSERT INTO Orders (OrderID, FirstName, LastName, QuantityPurchased, PricePerItem) VALUES (2, 'Natalie', 'Lopez', 10, 1.25)INSERT INTO Orders (OrderID, FirstName, LastName, QuantityPurchased, PricePerItem) VALUES (3, 'Brenda', 'Harper', 5, 4)IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Products')AND TYPE IN (N'U'))DROP TABLE ProductsGOCREATE TABLE Products(ProductID INT NOT NULL,Description VARCHAR(45) NULL,Color VARCHAR(45) NULL)INSERT INTO Products (ProductID, Description, Color)VALUES (1, 'Chair A', 'Red')INSERT INTO Products (ProductID, Description)VALUES (2, 'Chair B')INSERT INTO Products (ProductID, Description, Color) VALUES (3, 'Lamp C', 'Green')Statements from Book:SELECTLEFT ('sunlight',3) AS 'The Answer'SELECTRIGHT ('sunlight',5) AS 'The Answer'SELECTRIGHT (President,10) AS 'Last Name'FROM table1SELECTSUBSTRING ('thewhitegoat', 4, 5) AS 'The Answer' SELECTLTRIM (' the apple') AS 'The Answer'SELECTUPPER ('Abraham Lincoln') AS 'Convert to Uppercase', LOWER ('ABRAHAM LINCOLN') AS 'Convert to Lowercase' SELECTRIGHT (RTRIM (President),10) AS 'Last Name'FROM table1SELECTRIGHT ('George Washington', 10)SELECT GETDATE ()SELECT DATEPART (month, '7/2/2009')SELECT DATEPART (day, '7/2/2009')SELECT DATEPART (week, '7/2/2009')SELECT DATEPART (weekday, '7/2/2009')SELECT DATEDIFF (day, '2009-07-08', '2009-08-14') SELECT DATEDIFF (week, '2009-07-08', '2009-08-14') SELECT DATEDIFF (month, '2009-07-08', '2009-08-14') SELECT DATEDIFF (year, '2009-07-08', '2009-08-14') SELECT ROUND (712.863, 3)SELECT ROUND (712.863, 2)SELECT ROUND (712.863, 1)SELECT ROUND (712.863, 0)SELECT ROUND (712.863, -1)SELECT ROUND (712.863, -2)SELECT RAND ( )SELECT RAND (100)SELECT PI ( )SELECT ROUND (PI ( ), 2)SELECT'2009-04-11' AS 'Original Date',CAST('2009-04-11' AS DATETIME) AS 'Converted Date' SELECTDescription,ColorFROM ProductsSELECTDescription,ISNULL (Color, 'Unknown') AS 'Color'FROM ProductsChapter 5Setup Script:IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Customers')AND TYPE IN (N'U'))DROP TABLE CustomersGOCREATE TABLE Customers(CustomerID INT NOT NULL,FirstName VARCHAR(45) NULL,LastName VARCHAR (45) NULL)INSERT INTO Customers (CustomerID, FirstName, LastName) VALUES (1, 'William', 'Smith') INSERT INTO Customers (CustomerID, FirstName, LastName) VALUES (2, 'Janet', 'Smith') INSERT INTO Customers (CustomerID, FirstName, LastName) VALUES (3, 'Natalie', 'Lopez') INSERT INTO Customers (CustomerID, FirstName, LastName) VALUES (4, 'Brenda', 'Harper') IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'table1')AND TYPE IN (N'U'))DROP TABLE table1GOCREATE TABLE table1(TableID INT NOT NULL,CharacterData VARCHAR(45) NULL,NumericData INT NULL)INSERT INTO table1 (TableID, CharacterData, NumericData) VALUES (1, '23', 23)INSERT INTO table1 (TableID, CharacterData, NumericData) VALUES (2, '5', 5)INSERT INTO table1 (TableID, CharacterData) VALUES (3, 'Dog')INSERT INTO table1 (TableID, NumericData) VALUES (4, -6)Statements from Book:SELECTFirstName,LastNameFROM CustomersORDER BY LastNameSELECTFirstName,LastNameFROM CustomersORDER BY FirstNameSELECTFirstName,LastNameFROM CustomersORDER BY FirstName ASCSELECTFirstName,LastNameFROM CustomersORDER BY FirstName DESC SELECTFirstName,LastNameFROM CustomersORDER BY LastName, FirstName SELECTLastName + ', ' + FirstName AS 'Name' FROM CustomersORDER BY NameSELECTFirstName,LastNameFROM CustomersORDER BY LastName + FirstName SELECT NumericDataFROM table1ORDER BY NumericDataSELECTISNULL (NumericData, 0)FROM table1ORDER BY ISNULL (NumericData,0) SELECTCharacterDataFROM table1ORDER BY CharacterDataChapter 6Setup Script - Part 1:IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Products')AND TYPE IN (N'U'))DROP TABLE ProductsGOCREATE TABLE Products(ProductID INT NOT NULL,CategoryCode VARCHAR(45) NULL,ProductDescription VARCHAR (45) NULL)INSERT INTO Products (ProductID, CategoryCode, ProductDescription) VALUES (1, 'F', 'Apple') INSERT INTO Products (ProductID, CategoryCode, ProductDescription) VALUES (2, 'F', 'Orange') INSERT INTO Products (ProductID, CategoryCode, ProductDescription) VALUES (3, 'S','Mustard')INSERT INTO Products (ProductID, CategoryCode, ProductDescription) VALUES (4, 'V', 'Carrot') Statements from Book:SELECTCASE CategoryCodeWHEN 'F' THEN 'Fruit'WHEN 'V' THEN 'Vegetable'ELSE 'Other'END AS 'Category',ProductDescription AS 'Description'FROM ProductsSELECTCASEWHEN CategoryCode = 'F' THEN 'Fruit'WHEN CategoryCode = 'V' THEN 'Vegetable'ELSE 'Other'END AS 'Category',ProductDescription AS 'Description'FROM ProductsSetup Script - Part 2:IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Products')AND TYPE IN (N'U'))DROP TABLE ProductsGOCREATE TABLE Products(ProductID INT NOT NULL,Fruit VARCHAR(45) NULL,Vegetable VARCHAR (45) NULL,Spice VARCHAR (45) NULL,ProductDescription VARCHAR (45) NULL)INSERT INTO Products (ProductID, Fruit, Vegetable, Spice, ProductDescription) VALUES (1, 'X', ' ', ' ', 'Apple')INSERT INTO Products (ProductID, Fruit, Vegetable, Spice, ProductDescription) VALUES (2, 'X', ' ', ' ', 'Orange')INSERT INTO Products (ProductID, Fruit, Vegetable, Spice, ProductDescription) VALUES (3, ' ', ' ', 'X', 'Mustard')INSERT INTO Products (ProductID, Fruit, Vegetable, Spice, ProductDescription) VALUES (4, ' ', 'X', ' ', 'Carrot')Statements from Book:SELECTCASEWHEN Fruit = 'X' THEN 'Fruit'WHEN Vegetable = 'X' THEN 'Vegetable'ELSE 'Other'END AS 'Category',ProductDescription AS 'Description'FROM ProductsChapter 7Setup Script:IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Orders')AND TYPE IN (N'U'))DROP TABLE OrdersGOCREATE TABLE Orders(OrderID INT NOT NULL,FirstName VARCHAR(45) NULL,LastName VARCHAR (45) NULL,QuantityPurchased INT NULL,PricePerItem FLOAT NULL)INSERT INTO Orders (OrderID, FirstName, LastName, QuantityPurchased, PricePerItem) VALUES (1, 'William', 'Smith', 4, 2.5)INSERT INTO Orders (OrderID, FirstName, LastName, QuantityPurchased, PricePerItem) VALUES (2, 'Natalie', 'Lopez', 10, 1.25)INSERT INTO Orders (OrderID, FirstName, LastName, QuantityPurchased, PricePerItem) VALUES (3, 'Brenda', 'Harper', 5, 4)IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Books')AND TYPE IN (N'U'))DROP TABLE BooksGOCREATE TABLE Books(BookID INT NOT NULL,Title VARCHAR(45) NULL,Author VARCHAR (45) NULL,CurrentMonthSales INT NULL)INSERT INTO Books (BookID, Title, Author, CurrentMonthSales) VALUES (1, 'Pride and Prejudice', 'Austen', 15)INSERT INTO Books (BookID, Title, Author, CurrentMonthSales) VALUES (2, 'Animal Farm','Orwell', 7)INSERT INTO Books (BookID, Title, Author, CurrentMonthSales) VALUES (3, 'Merchant of Venice', 'Shakespeare', 5)INSERT INTO Books (BookID, Title, Author, CurrentMonthSales) VALUES (4, 'Romeo and Juliet', 'Shakespeare', 8)INSERT INTO Books (BookID, Title, Author, CurrentMonthSales) VALUES (5, 'Oliver Twist','DIckens', 3)INSERT INTO Books (BookID, Title, Author, CurrentMonthSales) VALUES (6, 'Candide', 'Voltaire', 9)INSERT INTO Books (BookID, Title, Author, CurrentMonthSales) VALUES (7, 'The Scarlet Letter', 'Hawthorne', 12)INSERT INTO Books (BookID, Title, Author, CurrentMonthSales) VALUES (8, 'Hamlet','Shakespeare', 2)Statements from Book:SELECTFirstName,LastName,QuantityPurchasedFROM OrdersWHERE LastName = 'Harper'SELECTFirstName,LastName,QuantityPurchasedFROM OrdersWHERE QuantityPurchased = 5SELECTFirstName,LastName,QuantityPurchasedFROM OrdersWHERE QuantityPurchased > 6SELECTFirstName,LastNameFROM OrdersWHERE LastName > 'K'SELECTTOP 3Title AS 'Book Title',CurrentMonthSales AS 'Quantity Sold'FROM BooksORDER BY CurrentMonthSales DESCSELECTTOP 1Title AS 'Book Title',CurrentMonthSales AS 'Quantity Sold'FROM BooksWHERE Author = 'Shakespeare'ORDER BY CurrentMonthSales DESCChapter 8Setup Script:IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Orders')AND TYPE IN (N'U'))DROP TABLE OrdersGOCREATE TABLE Orders(OrderID INT NOT NULL,CustomerName VARCHAR (45) NULL,State VARCHAR (45) NULL,QuantityPurchased INT NULL,PricePerItem FLOAT NULL)INSERT INTO Orders (OrderID, CustomerName, State, QuantityPurchased, PricePerItem) VALUES (1, 'William Smith', 'IL', 4, 2.5)INSERT INTO Orders (OrderID, CustomerName, State, QuantityPurchased, PricePerItem) VALUES (2, 'Natalie Lopez', 'CA', 10, 1.25)INSERT INTO Orders (OrderID, CustomerName, State, QuantityPurchased, PricePerItem) VALUES (3, 'Brenda Harper', 'NY', 5, 4)IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Products')AND TYPE IN (N'U'))DROP TABLE ProductsGOCREATE TABLE Products(ProductID INT NOT NULL,ProductDescription VARCHAR(45) NULL,Weight INT NULL)INSERT INTO Products (ProductID, ProductDescription) VALUES (1, 'Printer A')INSERT INTO Products (ProductID, ProductDescription, Weight) VALUES (2, 'Printer B', 0) INSERT INTO Products (ProductID, ProductDescription, Weight) VALUES (3, 'Monitor C', 2) INSERT INTO Products (ProductID, ProductDescription, Weight) VALUES (4, 'Laptop D', 4) Statements from Book:SELECTCustomerName,QuantityPurchasedFROM OrdersWHERE QuantityPurchased > 3 AND QuantityPurchased < 7 SELECTCustomerName, QuantityPurchased, PricePerItemFROM OrdersWHERE QuantityPurchased > 8 OR PricePerItem > 3SELECTCustomerName,State,QuantityPurchasedFROM OrdersWHERE State = 'IL'OR State = 'CA'AND QuantityPurchased > 8 SELECTCustomerName,State,QuantityPurchasedFROM OrdersWHERE (State = 'IL'OR State = 'CA')AND QuantityPurchased > 8 SELECTCustomerName,State,QuantityPurchasedFROM OrdersWHERE State = 'NY'OR (State = 'IL'AND (QuantityPurchased >= 3 AND QuantityPurchased <= 10)) SELECTCustomerName,State,QuantityPurchasedFROM OrdersWHERE NOT State = 'NY' SELECTCustomerName,State,QuantityPurchasedFROM OrdersWHERE State <> 'NY' SELECTCustomerName,State,QuantityPurchasedFROM OrdersWHERE NOT (State = 'IL'OR State = 'NY')SELECTCustomerName,State,QuantityPurchasedFROM OrdersWHERE State <> 'IL'AND State <> 'NY'SELECTCustomerName,State,QuantityPurchasedFROM OrdersWHERE NOT (State = 'IL'AND QuantityPurchased > 3)SELECTCustomerName,State,QuantityPurchasedFROM OrdersWHERE State <> 'IL'OR QuantityPurchased <= 3SELECTCustomerName,QuantityPurchasedFROM OrdersWHERE QuantityPurchased >= 5AND QuantityPurchased <= 20SELECTCustomerName,QuantityPurchasedFROM OrdersWHERE QuantityPurchased BETWEEN 5 AND 20 SELECTCustomerName,QuantityPurchasedFROM OrdersWHERE QuantityPurchased NOT BETWEEN 5 AND 20 SELECTCustomerName,StateFROM OrdersWHERE State = 'IL'OR State = 'NY'SELECTCustomerName,StateFROM OrdersWHERE State IN ('IL', 'NY') SELECTCustomerName,StateFROM OrdersWHERE State NOT IN ('IL', 'NY') SELECT ProductDescription,WeightFROM ProductsWHERE Weight = 0SELECT ProductDescription,WeightFROM ProductsWHERE Weight = 0OR Weight IS NULLSELECT ProductDescription,WeightFROM ProductsWHERE ISNULL (Weight, 0) = 0 SELECT ProductDescription,ISNULL (Weight, 0) AS 'Weight' FROM ProductsWHERE Weight = 0OR Weight IS NULLChapter 9Setup Script:IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Movies')AND TYPE IN (N'U'))DROP TABLE MoviesGOCREATE TABLE Movies(MovieID INT NOT NULL,MovieTitle VARCHAR(45) NULL)INSERT INTO Movies (MovieID, MovieTitle) VALUES (1, 'Love Actually')INSERT INTO Movies (MovieID, MovieTitle) VALUES (2, 'His Girl Friday')INSERT INTO Movies (MovieID, MovieTitle) VALUES (3, 'Love and Death')INSERT INTO Movies (MovieID, MovieTitle) VALUES (4, 'Sweet and Lowdown')INSERT INTO Movies (MovieID, MovieTitle) VALUES (5, 'Everyone Says I Love You') INSERT INTO Movies (MovieID, MovieTitle) VALUES (6, 'Down with Love')INSERT INTO Movies (MovieID, MovieTitle) VALUES (7, 'One Hundred and One Dalmations') IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Actors')AND TYPE IN (N'U'))DROP TABLE ActorsGOCREATE TABLE Actors(ActorID INT NOT NULL,FirstName VARCHAR(45) NULL,LastName VARCHAR(45) NULL)INSERT INTO Actors (ActorID, FirstName, LastName) VALUES (1, 'Cary', 'Grant')INSERT INTO Actors (ActorID, FirstName, LastName) VALUES (2, 'Mary', 'Steenburgen') INSERT INTO Actors (ActorID, FirstName, LastName) VALUES (3, 'Jon', 'Voight')INSERT INTO Actors (ActorID, FirstName, LastName) VALUES (4, 'Dustin', 'Hoffman') INSERT INTO Actors (ActorID, FirstName, LastName) VALUES (5, 'John', 'Wayne')INSERT INTO Actors (ActorID, FirstName, LastName) VALUES (6, 'Gary', 'Cooper')INSERT INTO Actors (ActorID, FirstName, LastName) VALUES (7, 'Julie', 'Andrews')Statements from Book: SELECTMovieTitle AS 'Movie'FROM MoviesWHERE MovieTitle LIKE '%LOVE%' SELECTMovieTitle AS 'Movie'FROM MoviesWHERE MovieTitle LIKE 'LOVE%' SELECTMovieTitle AS 'Movie'FROM MoviesWHERE MovieTitle LIKE '%LOVE' SELECTMovieTitle AS 'Movie'FROM MoviesWHERE MovieTitle LIKE '% LOVE %' SELECTFirstName,LastNameFROM ActorsWHERE FirstName LIKE '_ARY' SELECTFirstName,LastNameFROM ActorsWHERE FirstName LIKE 'J_N' SELECTFirstName,LastNameFROM ActorsWHERE FirstName LIKE '[CM]ARY' SELECTFirstName,LastNameFROM ActorsWHERE FirstName LIKE '[^CG]ARY' SELECTFirstName,LastNameFROM ActorsWHERE FirstName LIKE '%ARY%' AND FirstName NOT LIKE '[MG]ARY' SELECTSOUNDEX ('Smith') AS 'Sound of Smith',SOUNDEX ('Smythe') AS 'Sound of Smythe'SELECTDIFFERENCE ('Smith', 'Smythe') AS 'The Difference' SELECTFirstName,LastNameFROM ActorsWHERE DIFFERENCE (FirstName, 'John') = 4 SELECTFirstName,LastName,DIFFERENCE (FirstName, 'John') AS 'Difference Value', SOUNDEX (FirstName) AS 'Soundex Value'FROM ActorsChapter 10Setup Script:IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'SongTitles')AND TYPE IN (N'U'))DROP TABLE SongTitlesGOCREATE TABLE SongTitles(SongID INT NOT NULL,Artist VARCHAR(45) NULL,Album VARCHAR(45) NULL,Title VARCHAR(45) NULL)INSERT INTO SongTitles (SongID, Artist, Album, Title) VALUES (1, 'The Beatles', 'Abbey Road', 'Come Together')INSERT INTO SongTitles (SongID, Artist, Album, Title) VALUES (2, 'The Beatles', 'Abbey Road', 'Sun King')INSERT INTO SongTitles (SongID, Artist, Album, Title) VALUES (3, 'The Beatles', 'Revolver','Yellow Submarine')INSERT INTO SongTitles (SongID, Artist, Album, Title) VALUES (4, 'The Rolling Stones', 'Let It Bleed', 'Monkey Man')INSERT INTO SongTitles (SongID, Artist, Album, Title) VALUES (5, 'The Rolling Stones','Flowers', 'Ruby Tuesday')INSERT INTO SongTitles (SongID, Artist, Album, Title) VALUES (6, 'Paul McCartney', 'Ram','Smile Away')IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Fees')AND TYPE IN (N'U'))DROP TABLE FeesGOCREATE TABLE Fees(FeeID INT NOT NULL,Student VARCHAR(45) NULL,FeeType VARCHAR(45) NULL,Fee INT NULL)INSERT INTO Fees (FeeID, Student, FeeType, Fee) VALUES (1, 'George', 'Gym', 30)INSERT INTO Fees (FeeID, Student, FeeType, Fee) VALUES (2, 'George', 'Lunch', 10) INSERT INTO Fees (FeeID, Student, FeeType, Fee) VALUES (3, 'George', 'Trip', 8)INSERT INTO Fees (FeeID, Student, FeeType, Fee) VALUES (4, 'Janet', 'Gym', 30)INSERT INTO Fees (FeeID, Student, FeeType, Fee) VALUES (5, 'Alan', 'Lunch', 10)IF EXISTS(SELECT * FROM sys.objectsWHERE OBJECT_ID = OBJECT_ID (N'Grades')AND TYPE IN (N'U'))DROP TABLE GradesGOCREATE TABLE Grades(GradeID INT NOT NULL,Student VARCHAR(45) NULL,GradeType VARCHAR(45) NULL,Grade decimal NULL)INSERT INTO Grades (GradeID, Student, GradeType, Grade) VALUES (1, 'Susan', 'Quiz', 92) INSERT INTO Grades (GradeID, Student, GradeType, Grade) VALUES (2, 'Susan', 'Quiz', 95) INSERT INTO Grades (GradeID, Student, GradeType, Grade) VALUES (3, 'Susan', 'Homework', 84)INSERT INTO Grades (GradeID, Student, GradeType, Grade) VALUES (4, 'Kathy', 'Quiz', 62) INSERT INTO Grades (GradeID, Student, GradeType, Grade) VALUES (5, 'Kathy', 'Quiz', 81) INSERT INTO Grades (GradeID, Student, GradeType) VALUES (6, 'Kathy', 'Homework')INSERT INTO Grades (GradeID, Student, GradeType, Grade) VALUES (7, 'Alec', 'Quiz', 58) INSERT INTO Grades (GradeID, Student, GradeType, Grade) VALUES (8, 'Alec', 'Quiz', 74) INSERT INTO Grades (GradeID, Student, GradeType, Grade) VALUES (9, 'Alec', 'Homework', 88) Statements from Book:SELECTDISTINCTArtistFROM SongTitlesORDER BY ArtistSELECTDISTINCTArtist,AlbumFROM SongTitlesORDER BY Artist, AlbumSELECTSUM (Fee) AS 'Total Gym Fees'FROM FeesWHERE FeeType = 'Gym'SELECTAVG (Grade) AS 'Average Quiz Score'FROM GradesWHERE GradeType = 'Quiz'SELECTAVG (Grade) AS 'Average Quiz Score',MIN (Grade) AS 'Minimum Quiz Score',MAX (Grade) AS 'Maximum Quiz Score'FROM GradesWHERE GradeType = 'Quiz'SELECTCOUNT (*) AS 'Count of Homework Rows'FROM GradesWHERE GradeType = 'Homework'SELECTCOUNT (Grade) AS 'Count of Homework Scores' FROM GradesWHERE GradeType = 'Homework'SELECTCOUNT (DISTINCT FeeType) AS 'Number of Fee Types' FROM FeesSELECTGradeType AS 'Grade Type',AVG (Grade) AS 'Average Grade'FROM GradesGROUP BY GradeTypeORDER BY GradeTypeNOTE: The following statement intentionally errors. SELECTGradeType AS 'Grade Type',AVG (Grade) AS 'Average Grade',Student AS 'Student'FROM GradesGROUP BY GradeTypeORDER BY GradeTypeSELECTGradeType AS 'Grade Type',Student AS 'Student',AVG (Grade) AS 'Average Grade'FROM GradesGROUP BY GradeType, StudentORDER BY GradeType, StudentSELECTGradeType AS 'Grade Type',Student AS 'Student',AVG (Grade) AS 'Average Grade'。