Table of contents
Perform crud operations on tables
replace
replace(string, replaced characters, replaced characters)
For example:
select replace(replace(replace('May 18, 2012','Year','-'),'Day',' '),'Month','-');
create database
create database question1 on primary ( name='question1_data', filename='C:\temp\question1_data.mdf', size=5MB, maxsize=10MB, filegrowth=10% ) log on ( name='question1_log', filename='C:\temp\question1_log.ldf', size=5MB, maxsize=10MB, filegrowth=15% )
create table
use question1; create table city( CityCode Char(4) primary key, //主键 CityName Varchar(80) not null //非空 ) create table publishers( PubCode Char(4) primary key, PubName Char(5) not null, Phone Char(15), Address Varchar(100), CityCode Char(4) foreign key references city(CityCode) //外键 )
modify table
use question1; // Add column alter table publishers add comment Varchar(100) // Modify column length alter table publishers alter column comment Varchar(120) // Delete column comment alter table publishers drop column comment
delete table
//First delete the table with foreign key drop table publishers; drop table city;
Perform crud operations on tables
Price as price from titles where CategoryID=1 // Data screening, query the publication records in the titles table of the examDB database with publication dates from 2009 to 2010, and sort them in ascending order of publication date. order by default ascending * from titles where year(PubDate)>=2009 and YEAR(PubDate)<=2010 order by PubDate // Fuzzy query, query the publication record containing "database" in the titles table of the examDB database select * from titles where TitleName like '%database%' // Fuzzy query, query the publishing house in the titles table of the examDB database The second digit of the code is the publication name, author and publisher code of "X" select TitleName,Author,PubCode from titles where PubCode like '_X__' // Arithmetic operators are used in the query: query the price of the titles table in the examDB database More than 35 publication titles, prices and prices after 15% off select TitleName title, Price full price, Price*0.85 as '15% off' from titles where price>35
string functions
print len('HI - hello!') -- return 6 print datalength('123A Hello!') -- return 10 print datalength(N'123A Hello!') -- return 16 using unicode numbers and The letters occupy two bytes 3.upper ()--lowercase to uppercase 4.lower ()--uppercase to lowercase 5.ltrim () removes the space at the left end, rtrim() removes the space on the right 6.left ( 'NIHAOYAP,2') intercept 2 characters from the left 7.right ('NIAH',2) intercept 2 characters from the right 8.substring ('nihaooo',1,2)--intercept two characters from position 1 character, the result is ni, and the subscript starts from 1. print substring('nihaooo',-1,3)--The result returns n, the following table -1, 0 is a null value//, query the titles table in the examDB database for the TitleCode, the last three digits, the last digit of the TitleCode and the publication name, name, and length of the publication name whose length is greater than 7, and arrange them in descending order of length // RTRIM() removes trailing spaces , LTRIM removes the header spaces select TitleCode,right(RTRIM(TitleCode),3) Id1,right(RIRTM(TitleCode),1) Id2, TitleName,len(TitleName) from titles where len(TitleName)>7 order by len (TitleName) desc
math function
--1. ABS(X) absolute value function; SELECT ABS(-2.0),ABS(2); --2. PE() returns the function of pi; SELECT PI(); --3. SQRT(X) square root Function; SELECT SQRT(9), SQRT(11); --4, RAND() and RAND(X) functions: return a random floating-point value n (0<=n<=1.0); SELECT RAND(), RAND (),RAND(); ----The random number generated when there is no parameter is different; SELECT RAND(5),RAND(5),RAND(3);--The same random number is generated when the parameter is the same; --5. ROUND(X,Y) function: round up, return the value closest to the parameter X, and keep the value to Y digits after the decimal point. If Y is a negative number, the Y digits from the left of the decimal point are all 0; SELECT ROUND ( 33333.333333,2),ROUND(33333.33333,-2),ROUND(33333,-2); --6, SIGN(X) function: return the symbol of the parameter; SELECT SIGN(3),SIGN(0),SIGN(- 3), SIGN(3.33), SIGN(-33.33); --7, CEILING(X) function: return the smallest integer not less than X; SELECT CEILING(33.333), CEILING(33.666), CEILING(-33.333), CEILING (-33.666); --8. FLOOR(X) function: return the largest integer smaller than X; SELECT FLOOR(33.333),FLOOR(-33.333); --9. POWER(X,Y) function: return x to the power of y; SELECT POWER(2,3),POWER(3,0),POWER(5,-2),POWER(5.0,-2), POWER(5.000,-2); --10, SQUARE(X) function: return the square of x; SELECT SQUARE(0), SQUARE(3), SQUARE(-3), SQUARE(3.3); --11, EXP (X) function: return the x power of e; SELECT EXP(3), EXP(-3), EXP(0), EXP(3.3); --12, LOG(X) function: return the natural logarithm of x , x cannot be 0 or negative; SELECT LOG(3.3), LOG(3), LOG(4); --13, LOG10(X) function: return the logarithm of x whose base is 10, such as 100 whose base is 10 The logarithm of is 2; SELECT LOG10(1000), LOG10(1), LOG10(5); --14, RADIANS(X) function: convert the parameter x from angle to radian; SELECT RADIANS(45.0), RADIANS(45 ),RADIANS(-45.0); --15, DEGREES(X): Function: convert the parameter x from radians to angles; SELECT DEGREES(33),DEGREES(33.33333),DEGREES(-33.33333),DEGREES(PI() ); --16, SIN (X) function: return the sine of x, x is the radian value; SELECT SIN(30),SIN(-30),SIN(PI()),SIN(PI()/2),ROUND(SIN(PI()),0); --17. ASIN(X) function: return the arcsine of x, that is, return the value whose sine is x; SELECT ASIN(1), ASIN(0), ASIN(-1); --18. COS(X) function : Return the cosine of x, x is the radian value; SELECT COS(30),COS(-30),COS(PI()),COS(1),COS(0); --19 , ACOS(X) function: Return the arc cosine of x, that is, return the value whose cosine is x; SELECT ACOS(1),ACOS(0),ACOS(-1),ACOS(0.3434235),ROUND(ACOS(0.3434235),1); --20 、 TAN(X) function: return the tangent of x, x is the radian value; SELECT TAN(1), TAN(0), TAN(-1); --21, ATAN(X) function: return the arc tangent of x, namely Return the value whose tangent is x; SELECT TAN(1), ATAN(1.5574077246549), ATAN(0); ------TAN and ATAN are mutually inverse functions; --22, COT(X) function: return the value of x Cotangent; SELECT COT(3),1/TAN(3),COT(-3);-------------------COT and TAN are reciprocals of each other;// Return an integer less than or equal to the following two numbers: 4.5 and -7.6; return an integer greater than or equal to 8.1; return 2 to the power of 5 select FLOOR(4.5), FLOOR(-7.6), CEILING(8.1), POWER (2,5);
date function
1.Current_Timestamp: return the current system time -- no parameters -- return datetime type select Current_Timestamp as current system time -- 2019-09-22 23:46:53.623 2.Dateadd(): add or subtract the specified date in the date Time interval --Syntax: Dateadd(datepart,number,date) --datepart: the part of the date to be added to the integer value --number: the number of time intervals, which can be positive or negative --date: date --Return datetime type select Dateadd(dd,3,Getdate()) --Return current time plus three days select Dateadd(mm,-3,Getdate())--Return current time minus three months 3.Datediff() : return time difference -- syntax Datediff(datepart, startdate, enddate) --datepart: unit used to report the difference between startdate and enddate --startdate: start date --enddate: end date -- return int type select Datediff(dd ,'2019-07-01','2019-07-25')--return 24 select Datediff(mm,'2019-11-01','2019-10-10')--return -1 4.Datename(): Returns a string representing the specified date part of the specified date --Syntax: Datename(datepart,date) --Returns the string type select Datename(dd,getdate())--Get the current day select Datename( mm, getdate())--Get the current month select Datename(yy, getdate())--Get the current year 5.Datepart(): Return an integer representing the specified date part of the specified date --Syntax: Datepart(datepart,date ) --return int type select Datepart(day,getdate())--get the current day select Datepart(month,getdate())--get the current month select Datepart(year,getdate())--get the current year 6.Day (): Returns an integer representing the "day" date part of the specified date -- Syntax: Day (datetime) -- returns int type select Day(getdate()) -- returns the current day select Day('2019-09-22' )--return 22 7.Getdate(): return the date and time of the current system --Syntax: Getdate() --return datetime type select Getdate() 8. Getutcdate(): Return the current UTC (Universal Coordinated Time, Universal Standard Time) time -- syntax: Getutcdate() -- return datetime type select Getutcdate() -- Beijing time minus eight hours 9.Isdate(): OK Whether the input expression is a valid date, return 1 for true, 0 for false --Syntax: Isdate(varchar) --return int type select Isdate('2019-20-01')--return 0 select Isdate('2019 -01-01')--return 1 10.Month(): return the integer of the "month" part of the specified date --Syntax: Month(datetime) --return: int type select Month(getdate())--return Current month select Month('2019-07-01')--return 7 11.Sysdatetime(): return the datetime2(7) value of the current system time --Syntax: Sysdatetime() --return datetime2(7) select Sysdatetime( ) 12.Sysdatetimeoffset(): returns the datetimeoffset(7) value of the current system time, including the time zone offset --Syntax: Sysdatetimeoffset() --returns the datetimeoffset type select Sysdatetimeoffset() 13.Sysutcdatetime(): Return the datetime2(7) value of the current UTC (Universal Standard Time) --Syntax: Sysutcdatetime() --Return: datetime2(7) type select Sysutcdatetime() 14.Switchoffset(): Change datetimeoffset value from reserved timezone offset to new value --Syntax: Switchoffset(datetimeoffset, timezone) --datetimeoffset: expression --Timezone: varchar --Return datetimeoffset DECLARE @dt datetimeoffset = switchoffset (CONVERT(datetimeoffset , GETDATE()), '-04:00') SELECT * FROM table_name WHERE dt2> @dt Option (Recompile) --Recompile, improve performance 15.Todatetimeoffset(): Return datetimeoffset value converted from datetime2 expression-- Syntax: Todatetimeoffset(expression, time zone) -- return datetimeoffset type DECLARE @todaysDateTime datetime2 SET @todaysDateTime = GETDATE() SELECT Todatetimeoffset (@todaysDateTime, '-07:00') 16. Year(): Returns the integer of the "year" part of the specified date -- Syntax: Year(datetime) -- returns int type select Year(getdate())--current year 17.Datepart parameters://Return the current system date, return the number of months between the two dates "2008-01-01" and "2009-01-01" yy returns the number of years mm returns the number of months, dd returns the number of days select GETDATE( ),DATEDIFF(mm ,'2008-01-01','2009-01-01')
aggregate function
1. COUNT aggregate function: Returns the number of query records (rows).
Format:
COUNT([ALL|DISTINCT][expression|*])Parameter Description:
ALL: The default value, which refers to the total number of statistics for all records queried.
DISTINCT: refers to the total number of deduplicated non-empty records for the query records.
Expression: refers to any type of expression except text, image, ntext;
*: Indicates the total number of rows in the query record.
2. SUM summation function: Calculate the total value of the data in the numeric column in the table.
Format:
SUM([ALL|DISTINCT] expression)ALL: The default value, refers to the summation of all records in the query.
DISTINCT: refers to deduplicating the query records and summing them.
Expression: Any combination of constants, data columns, functions, and arithmetic operations.
usage:
SELECT SUM(score) FROM T_Score SELECT SUM(DISTINCT score) FROM T_Score SELECT SUM(1+99) 3. AVG average function: return the average value in the data list, NULL is ignored.
Format:
AVG([ALL|DISTINCT] column name (numeric type))Parameters: ALL: Indicates all columns that are not NULL, DISTINCT deduplicated columns.
usage:
SELECT AVG(Age) FROM T_User -- Calculate the average age SELECT AVG(DISTINCT Age) FROM T_User -- Calculate the average age after deduplication 4. MAX/MIN: Find the maximum/minimum value of the data in any column in the table.
Format:
MAX/MIN(column name)usage:
SELECT MAX(score) FROM T_Score SELECT MIN(score) FROM T_Score 5. COUNT_BIG aggregate function: Usage is similar to COUNT, the only difference is that the value type returned by COUNT_BIG is bigint, and the value type returned by COUNT is int.
6. Function of GROUPING function: add an additional column. If the grouping() function returns 1, it indicates aggregation; if it returns 0, it indicates no aggregation.
usage:
SELECT GROUPING(name),name from T_User GROUP BY name
//Query the average price of all publications in the titles table of the examDB database select avg(Price) from titles; //Use GROUP BY in the SELECT statement: create a new query window, enter the query statement, and realize the statistics of each publication in the publishers table of the examDB database The number of publishers in the city select count(*) as the number of publishers, citycode from publishers group by CityCode order by count(*) //Use HAVING in the SELECT statement (used together with GROUP BY): Create a new query window and enter the query statement , to achieve statistics in the examDB database publishers table select CityCode from publishers group by CityCode having count(*)>1
multi-table query
--Join query --Query customer name, purchase quantity, purchase unit price, commodity name --Method 1: Inner join: inner join Syntax: select column name 1, column name 2... from table name 1 inner join table name 2 on (foreign key table. foreign key = primary key table. primary key) --query customer name, purchase quantity, purchase unit price, product name select clientName, productNumber, salePrice, productName from sales inner join product on(sales.productId=product.productId ) --Query customer name, product name, product price select clientName, productName, price from sales s inner join product p on(s.productId=p.productId) --Method 2: Realize inner connection query through equivalence connection: select Column name 1, column name 2... from table name 1, table name 2 where foreign key table. foreign key = primary key table. primary key select clientName, productName, price from sales s, product p where s.productId=p.productId --Query the product name, sales unit price and sales quantity of single sales quantity > 20 select productName, salePrice, productNumber from product inner join sales on(product.productId=sales.productId) where productNumber>20 select productName, salePrice, productNumber from product, sales where product.productId=sales.productId and productNumber>20 --empdb use empdb select * from dept select * from emp --query employee name, gender, address, department name and department number select empName,empSex,empAddress,deptName,deptNum from emp inner join dept on(emp.deptId=dept.deptId) --query the name, gender, address, department name and department number of employees whose name appears "Kaige" select empName, empSex,empAddress,deptName,deptNum from emp inner join dept on(emp.deptId=dept.deptId) where empName like '%Kaige%' select empName,empSex,empAddress,deptName,deptNum from emp,dept where emp.deptId=dept .deptId and empName like '%Kaige%'//Use multiple tables in one SELECT statement (inner join): Create a new query window, enter a query statement, and query the publisher name (in the publishers table) of each city (CityName in the city table) in the examDB database select CityName , pubName from city inner join publishers on(city.CityCode=publishers.CityCode) //Use a subquery in the SELECT statement: Create a new query window, enter a query statement, and query the publication name, author and name of the publication with the highest price in the publishers table of the examDB database Publication date select TitleName,Author,PubDate from titles where Price=(select max(Price) from titles) //Set operation using UNION operator: Create a new query window, enter the query statement, query the CityCode in the publishers table of the examDB database is "AGZ "Publication information: including the record set of PubCode, PubName, Phone, CityCode, and the publishing house information with CityCode as "HBJ": including the record set of PubCode, PubName, Phone, CityCode, perform union operation select PubCode,PubName , Phone,CityCode from publishers where CityCode='AGZ' union select PubCode,PubName,Phone,CityCode from publishers where CityCode='HBJ'
variable
local variable
Identifiers starting with "@" represent variables (local variables), which must be declared with the DECLARE command before they can be used:
DECLARE @js_age int; DECLARE @name varchar(32), @address varchar(64);After using the DECLARE command and creating a local variable, the initial value is NULL, you can use SELECT or SET to command the value of this local variable, example 1: declaration, assignment, output:
DECLARE @js_age INT SELECT @js_age = 28 SELECT @js_age AS 年龄 GO
Example 2: Assigning values to variables through query statements:
DECLARE @js_rows INT SET @js_rows = (SELECT COUNT(*) FROM PERSON) SELECT @js_rows as 行数 GO
Example 3: Query using a local variable assigned by SET:
USE test GO DECLARE @js_address VARCHAR(64) SET @js_address = 'AAAAA' SELECT RTRIM(FirstName) + ' ' + RTRIM(LastName) AS Name, @js_address AS ADDRESS FROM PERSON GO
global variable
In SQL Server, global variables are a special type of variable whose values are maintained by the server. Global variables start with the @@ prefix and do not need to be declared, they belong to the functions defined by the system.
@@CONNECTIONS returns the number of connections SQL Server has attempted since it was last started. @@CPU_BUSY returns the working time of SQL Server since it was last started. @@CURSOR_ROWS returns the number of currently qualifying rows in the last cursor opened on the connection, determining the number of rows eligible for the cursor that were retrieved when it was called. @@DATEFIRST Returns for the session the current value of SET DATEFIRST, which represents the specified first day of the week. @@DBTS returns the value of the current timestamp data type of the current database, which must be unique in the database. @@ERROR Returns the error number of the last Transact-SQL statement executed, or 0 if the previous Transact-SQL statement was executed without error. @@FETCH_STATUS returns the status of the last cursor FETCH statement issued against any cursor currently open on the connection . @@IDENTITY returns the last inserted identity value. @@IDLE Returns the amount of time SQL Server has been idle since it was last started. Results are expressed in increments of CPU time , or "clock cycles," and are cumulative across all CPUs. @@IO_BUSY Returns the time Microsoft SQL Server has spent performing input and output operations since SQL Server was last started. The result is a CPU time increment (clock cycle) and is cumulative across all CPUs @@LANGID returns the local language identifier (ID) of the language currently in use. @@LANGUAGE Returns the name of the language currently in use. @@LOCK_TIMEOUT: Returns the current lock timeout setting (in milliseconds) for the current session. @@MAX_CONNECTIONS Returns the maximum number of simultaneous user connections allowed by the instance of SQL Server. The returned value is not necessarily the currently configured value. @@MAX_PRECISION Returns the precision level used for the decimal and numeric data types according to the current setting in the server . @@NESTLEVEL returns the nesting level of the current stored procedure executed on the local server (initial value is 0). @@OPTIONS returns information about the current SET options. @@PACK_RECEIVED returns the number of input packets SQL Server has read from the network since it was last started. @@PACK_SENT returns the number of output packets that SQL Server has written to the network since it was last started. @@PACKET_ERRORS Returns the number of network packet errors that have occurred on SQL Server connections since SQL Server was last started . @@PROCID returns the object identifier (ID) of the current Transact-SQL module. Transact-SQL modules can be stored procedures, user-defined functions, or triggers. @@REMSERVER returns the name of the remote SQL Server database server as it appears in login records. @@ROWCOUNT returns the number of rows affected by the previous statement. @@SERVERNAME returns the name of the local server running SQL Server. @@SERVICENAME returns the name of the registry key under which SQL Server is running. @@SERVICENAME returns MSSQLSERVER if the current instance is the default instance. @@SPID returns the session ID of the current user process. @@TEXTSIZE returns the current value of the TEXTSIZE option in the SET statement. @@TIMETICKS returns the number of microseconds per clock tick. @@TOTAL_ERRORS returns the number of disk write errors SQL Server has encountered since it was last started. @@TOTAL_READ returns the number of times SQL Server has read from disk (not the read cache) since it was last started. @@TOTAL_WRITE Returns the number of disk writes SQL Server has performed since it was last started. @@TRANCOUNT returns the number of active transactions for the current connection. @@VERSION returns the current SQL Server installation's version, processor architecture, build date, and operating system.
Use print to output numbers and strings together
If you want to output on the same line, you must make the output type consistent, that is to say, the output string and the numeric type must be consistent . Obviously, it is easier to convert the numeric value into a string, so we can use print @p+ convert(varchar,@q) where @p is a string type and @q is a numeric type
DECLARE @vname Char(10); DECLARE @vnum int; set @vname = 'Zhang San'; set @vnum = 12; print 'Local variable:' + '@vname:'+@vname+'@vnum:'+convert (varchar,@vnum) print 'Global variable:' + '@@Language (the name of the current language):'+ @@Language;
cast function
built-in function
Syntax: CAST (expression AS data_type) Parameter description: expression: any valid SQServer expression. AS: used to separate two parameters, before AS is the data to be processed, after AS is the data type to be converted. data_type: The data types provided by the target system, including bigint and sql_variant, cannot use user-defined data types.Note: (1). The parameter of the CAST() function is an expression, which includes the source value and target data type separated by the AS keyword. The following example is used to convert the text string '12' to an integer: SELECT CAST('12' AS int) (2). The return value is the integer value 12. What happens if you try to convert a string representing a decimal to an integer value? SELECT CAST('12.5' AS int) (3). Neither the CAST() function nor the CONVERT() function can perform rounding or truncation operations. Since 12.5 cannot be represented by the int data type, calling this function will generate an error: Server: Msg 245, Level 16, State 1, Line 1 Syntax error converting the varchar value '12.5' to a column of data type int. (4). To return a legal value, you must use a data type that can handle this value. For this example, there are several data types available. If the value is converted to a decimal type through the CAST() function, the precision and scale of the decimal value need to be defined first. In this example, the precision and scale are 9 and 2, respectively. Precision is the total number of digits, including the sum of digits to the left and right of the decimal point. And the number of decimal places is the number of digits to the right of the decimal point. This means that the largest integer value supported by this example is 9999999, and the smallest decimal value is 0.01. SELECT CAST('12.5' AS decimal(9,2)) The decimal data type will display significant decimal places in the results grid: 12.50 (5). The default values of precision and decimal places are 18 and 0 respectively. If these two values are not provided in the decimal type, SQL Server will truncate the decimal part of the number without generating an error. SELECT CAST('12.5' AS decimal) results in an integer value: 12Use the select output statement to output the value of the publication code and its corresponding price converted in characters using the CAST function select TitleCode,TitleName,Author,CateGoryID,PubCode,CAST(Price as varchar) 'Price',PubDate from titles;
view
CREATE VIEW <view name> [(<column name>[,<column name>]...)] AS <subquery> [WITH CHECK OPTION] //Delete view drop view view name
Notice:
When our SQL Server is creating a view, the syntax error prompt "create view must be the only statement in the batch" will appear. In fact, there is nothing wrong with this in itself! Because create view must be the first statement in the batch. In other words, you may have other statements before this code that are processed at the same time. For this reason, you can add GO to the line before this code, and add GO to the line after the end of this code. . . Or if you execute this code alone, there will be no error.
--Realize the creation of a view named view1 on the titles table in the examDB database, and query the TitleName, Author, Price and PubDate of publications published after 2010. --After the creation is successful, save the view and use the SELECT statement to view the columns contained in the view use examDB; go create view view1 as select TitleName,Author,Price,PubDate from titles where year(PubDate)>2010 go select * from view1;Create a complex view: Create a new query window, enter a Transact-SQL statement, and create a view named view2 in the examDB database. The view implements group statistics of various publications (TitleCode) by category ID (Category table) and category name (Category table) )quantity. use examDB; go create view view2 as select category.CategoryID as 'category ID', category.CategoryName 'category name', count(TitleCode) quantity from category left outer join titles on category.CategoryID=titles.CategoryID group by category.CategoryID ,category.CategoryName go select * from view2 Note: Both CategoryID and CategoryName are needed in the last group by group, because ID and Name are one-to-one correspondence
index
//Create index create index index name on table name (field) //delete index drop index table name.indexCreate an index named newidx on the pubdate field of the table titles create index newidx on titles(Pubdate)
stored procedure
create proc stored procedure name @input parameter data type, @output parameter data type output as begin stored procedure body end; // call stored procedure EXEC <procedure name> <input parameter value> [,<input parameter value>].. .//The stored procedure realizes that the cityName is "Beijing" in the city table, and the pubName and Address of the city are queried in the publishers table, that is, the name and address of the publishing house whose city name is "Beijing" is queried. create proc sproc1 as begin select pubName ,Address from publishers inner join city on city.CityCode=publishers.CityCode where city.CityName='Beijing' end; exec sproc1;// Create a new stored procedure named sproc2 in the examDB database. The stored procedure includes an input parameter for cityName. This stored procedure realizes that different cityNames are given in the city table, and the pubName and Address of the city are queried in the publishers table. use examDB; go create proc sproc2 @cname varchar(80) as begin select pubName,Address from publishers inner join city on publishers.CityCode =city.CityCode where city.CityName = @cname end exec sproc2 'Beijing'Create a new stored procedure named sproc3 in the examDB database. The stored procedure includes an input parameter and an output parameter: the input parameter indicates TitleCode, and the output parameter indicates Price. The stored procedure is implemented in the titles table to find the corresponding Price according to different publication codes. use examDB; go create proc sproc3 @tc char(6) , @p money output as begin select @p=Price from titles where TitleCode=@tc end go declare @p money exec sproc3 'T002',@p output; use examDB ; go create proc sproc3 @tc char(6) , @p money output as begin select @p=Price from titles where TitleCode=@tc end go declare @p money exec sproc3 'T002', @p output print 'T002's price is' + convert(varchar,@p); note: exec sproc3 'T002',@p output Do not add a semicolon between print 'T002's price is' + convert(varchar,@p) ;
trigger
create trigger trigger name on table name (after,before) (insert,delete,update) as begin if condition: update(PubDate) begin content end; end;//Realize the creation of a trigger named newtrigger in the examDB database. The trigger stipulates that when the data in the PubDate column of the titles table changes, the text "The publication date has changed. The trigger worked." is displayed. Modify the PubDate column data of the titles table to trigger the trigger use examDB; go create trigger newtrigger on titles after update as begin if update(PubDate) begin print 'The publication date has been modified, the trigger works' end end; update titles set PubDate='2011-06-02' where TitleCode='T001'
database user
Create database login account exec sp_addLogin account name account password Create database user exec sp_grantDBaccess login account usernameAuthorize grant (select,update,delete,…) on table name to user name for database usersCreate a database login account: Create a new query window, enter a Transact-SQL statement, and use the system stored procedure sp_addLogin to create a login account with SQL Server identity: the login name is Login1, and the password is 123456 exec sp_addLogin 'Login1','123456 'Create a database user: Create a new query window, select the database examDB, enter a Transact-SQL statement, and use the system stored procedure sp_grantdDBaccess to create a database user dbUser1 in the database (the default login name is Login1, which can also be different) exec sp_grantdDBaccess 'Login1',' dbUser1 'Grant the database user dbUser1 the select and update object permissions on the publishers table grant select, update on publishers to dbUser1