W3. SQL Stored Procedures Flashcards
Q: What is a stored procedure in SQL?
A: It’s a prepared SQL code that can be saved and reused, allowing you to execute complex queries repeatedly.
Q: Why would you use a stored procedure?
A: To avoid rewriting SQL queries and to execute complex SQL statements with a single call.
Q: Can you pass parameters to a stored procedure?
A: Yes, parameters can be passed so the procedure can operate based on specific values.
Q: Write the syntax to create a stored procedure.
CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
Q: How do you execute a stored procedure?
A: Use EXEC procedure_name;
Q: Write a stored procedure to select all records from Customers, named “SelectAllCustomers”.
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;
Q: How would you execute the stored procedure “SelectAllCustomers”?
EXEC SelectAllCustomers;
Q: How do you create a stored procedure with one parameter?
A: Define the parameter in the procedure, e.g.,
CREATE PROCEDURE procedure_name @Parameter datatype
AS
sql_statement;
Q: Write a stored procedure to select customers from a specific city, using @City as a parameter.
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)
AS
SELECT * FROM Customers WHERE City = @City
GO;
Q: How would you execute the “SelectAllCustomers” procedure with @City = ‘London’?
EXEC SelectAllCustomers @City = ‘London’;
Q: How do you create a stored procedure with multiple parameters?
A: Define each parameter with a datatype, separated by commas, e.g.,
CREATE PROCEDURE procedure_name @Param1 datatype, @Param2 datatype;
Q: Write a stored procedure to select customers from a specific city and postal code, using @City and @PostalCode as parameters.
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode nvarchar(10)
AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;
Q: How would you execute the “SelectAllCustomers” procedure with @City = ‘London’ and @PostalCode = ‘WA1 1DP’?
EXEC SelectAllCustomers @City = ‘London’, @PostalCode = ‘WA1 1DP’;