Please check my current stored procedure.
USE [CastingDatabase]
GO
/****** Object: StoredProcedure [dbo].[Searching_Talents] Script Date: 11/11/2015 1:41:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Searching_Talents]
#name nvarchar(100),
#age_from nvarchar(10),
#age_to nvarchar(10)
AS
BEGIN
SELECT *
FROM [dbo].[Talents]
WHERE(
((#name is null) or (#name='') or ([dbo].[Talents].[Name] LIKE '%'+#name+'%'))
AND
(((#age_to is null) or (#age_to='') or (DATEDIFF(YEAR,Talents.DOB,GETDATE()) IN
(
SELECT CAST (Item as int) FROM dbo.SplitString(#age_to,',')
)
))
)
)
ORDER BY Name
END
I want to add some if_else condition statements in second where clause.
How can I add?
I want to add like this
AND(if(#age_from is null){---- my codes ----})
P.S. I am a newbie in stored procedure. Please help me.
Add CASE where you want to check some value. This doesn't apply only for procedures, it applies on all queries in sql server
...
AND (
CASE
WHEN #age_from IS NULL
THEN yourCode
END
)
or if you have only to check if null and write something else, you can check it like this:
...
AND (ISNULL(#age_from, defaultValue)
and in this case, if value of age_from is null, sql server will put defaultValue which you state in above code.
Related
I've got a stored procedure that is coded similarly to the following:
USE [database]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[procedure_name]
#record_id int
, #record_value VARCHAR(MAX)
AS
BEGIN
UPDATE dbo.table_1
SET table_1_record_value = #record_value
WHERE table_1_record_int = #record_int
END
BEGIN
INSERT INTO table_2 COLUMNS (table_2_record_id, table_2_record_value) VALUES (#record_id, #record_value)
END
And I'm getting a syntax error. I've never had to write a stored procedure for an application that would accomplish both an UPDATE and an INSERT statement together.
The answer was provided by bbaird in the comments. Removing the BEGIN/END keywords fixed the problem. Thank you!
bbaird's full comment below:
If the procedure isn't created yet, you will need to do CREATE PROCEDURE. 2. The update and insert statements are independent, no need to put them in their own BEGIN...END block unless there is a conditional. 3. COLUMNS in the insert statement might also be throwing things off - it is not necessary so remove it.
The answers of Jake and bbard are correct.
Below the code of your stored procedure:
USE [database]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROC [dbo].[procedure_name]
#record_id int
, #record_value VARCHAR(MAX)
AS
BEGIN
UPDATE dbo.table_1
SET table_1_record_value = #record_value
WHERE table_1_record_int = #record_int
INSERT INTO table_2 COLUMNS (table_2_record_id, table_2_record_value)
VALUES (#record_id, #record_value)
END
For documentation of BEGIN and END look here
In my SQL Server 2012 database, I have a table MyTable, a view MyView and a scalar function MyFun.
The view will refer to MyFun as shown below:
CREATE VIEW [dbo].[MyView]
AS
SELECT dbo.MyFun(Age) AS Expr1
FROM dbo.MyTable
While the function will refer to MyView, as shown here:
CREATE FUNCTION [dbo].[MyFun] (#Age int)
RETURNS int
WITH EXECUTE AS CALLER
AS
BEGIN
SET #Age = (SELECT COUNT(*) FROM [db].[MyView]);
RETURN (#Age + 1);
END;
Since MyFun and MyView will cause circular reference, which one should be created first? I cannot find any documents on this.
I made a test.
First, I export the database as a script. Then I find in the script, the function is created first, as below:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[MyFun] (#Age int)
RETURNS int
WITH EXECUTE AS CALLER
AS
BEGIN
SET #Age = (SELECT COUNT(*) FROM [db].[MyView]);
RETURN(#Age + 1);
END;
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MyTable]
(
[Name] [nchar](10) NULL,
[Age] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[MyView]
AS
SELECT dbo.MyFun(Age) AS Expr1
FROM dbo.MyTable
GO
However, if I modify the script and put function creation after view creation, as below:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MyTable]
(
[Name] [nchar](10) NULL,
[Age] [int] NULL
) ON [PRIMARY]
GO
CREATE VIEW [dbo].[MyView]
AS
SELECT dbo.MyFun(Age) AS Expr1
FROM dbo.MyTable
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[MyFun] (#Age int)
RETURNS int
WITH EXECUTE AS CALLER
AS
BEGIN
SET #Age = (SELECT COUNT(*) FROM [db].[MyView]);
RETURN(#Age + 1);
END;
GO
Then the creation of view will report the following error:
Msg 4121, Level 16, State 1, Procedure MyView, Line 3 [Batch Start Line 17]
Cannot find either column "dbo" or the user-defined function or aggregate "dbo.MyFun", or the name is ambiguous.
So based on the test, for circular reference, the function should be created before the view, and the function can reference objects that have not been created yet.
But how about other objects, such as defaults, triggers, table-valued functions, stored procedures, etc. If they are circular refers to each other, then which one should be created first and which can be created later?
I have a master table "Repairs" and a detail table "RepairDetails" I am trying to write a procedure to update both tables when I send the appropriate parameters from my application. Here is my SQL:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[UpdateRepair]
#RepairID bigint,
#TypeID bigint = NULL,
#Directions nvarchar(3000) = NULL,
#NewDetails NewDetails READONLY
AS
BEGIN
SET NOCOUNT ON;
UPDATE Repairs
SET
TypeID = ISNULL(#TypeID, TypeID),
Directions = ISNULL(#Directions, Directions),
LastUpdate = SYSDATETIME()
WHERE RepairID = #RepairID;
IF #NewDetails IS NOT NULL UpdateRepairDetails;
END
where "NewDetails" is a User-defined table type and "UpdateRepairDetails" is a different stored procedure that takes #RepairID and #NewDetails as parameters.
I have an error and a question. The error message is:
Must declare the scalar variable "#NewDetails"
which I don't understand because it is defined.
And my question is: will the parameters "#RepairID" and "#NewDetails" get automatically passed to the "UpdateRepairDetails" procedure. If not, what is the proper approach to accomplish this?
You cannot assign NULL to a table variable. Hence you can't check whether a table variable is NULL.
Second: no. You should call as follows:
EXEC UpdateRepairDetails #RepairID, #NewDetails;
I am trying to implement a search functionality using JSP and SQL Server. I am required to search using keywords such a phone number. But my lecturer wants me to implement the search functionality a bit differently.
Let's say - I have a phone number in the database 123456 and I key in the number in the search box 123. The procedure should be able to retrieve all the records with the phone number that starts with 123.
I tried the following so far but I have to enter the full number for the results to be retrieved. How can I change my procedure so that it works the way my lecturer wants?
USE [test]
GO
/****** Object: StoredProcedure [dbo].[add_data] Script Date: 15-11-2016 10:14:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[select_data]
(
#thePhoneNumber VARCHAR(200),
#theName VARCHAR(200) OUT
)
As
Begin
SELECT #theName= Name FROM real WHERE PhoneNumber=#thePhoneNumber
End
I don't know if this is the answer you are looking for but for a normal SQL query you should use the % sign every time you want to search the rest.
For example in this context you should use:
SELECT phonenumber FROM real WHERE phonenumber LIKE '123%'
Hope it Helps :)
Like operator will help you in this case.
USE [test]
GO
/****** Object: StoredProcedure [dbo].[add_data] Script Date: 15-11-2016 10:14:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[select_data]
(
#thePhoneNumber VARCHAR(200),
#theName VARCHAR(200) OUT
)
As
Begin
SELECT #theName= Name FROM real WHERE PhoneNumber like '#thePhoneNumber+'%'
End
Well yeah, pretty specific.
I have a job that executes a SSIS Package. This package has a variable called "Email" which is a string.
I'm executing this job via stored procedure. I need to pass the value for that variable to the job, how do I do it?
This is the stored procedure I'm using to execute the job (#VarValue is the value I want to pass to the SSIS package):
USE [DevDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spChecklistEmail]
#JobName [nvarchar](100),
#VarValue [nvarchar](255),
#ReturnValue [int] OUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #JobId binary(16);
DECLARE #job_status INT
SELECT #JobId = job_id FROM msdb.dbo.sysjobs WHERE (name = #JobName);
SELECT #job_status = [dbo].[fn_GetJobStatus](#JobName);
IF (#job_status IN (2, 4))
BEGIN
SET #ReturnValue=#job_status;
END
ELSE
BEGIN
IF (#JobId IS NOT NULL)
BEGIN
EXEC #ReturnValue=msdb.dbo.sp_start_job #job_id=#JobId;
END
ELSE
BEGIN
SET #ReturnValue=-2;
END
END
RETURN (#ReturnValue)
END
There isn't any real easy way to do this. The only thing I can think of is to take that value and before you call the package create a table or temp table and load the variable into that table you created. After that you could then access that varibale in you ssis package for what you need to use it for. Don't forget to clean up the extra table and/or value after the job.
Check out this link: https://msdn.microsoft.com/en-us/library/jj820152.aspx
Specifically part 2.
Looks like you can create variables and set them in the EXEC statement.
EXEC #ReturnValue=msdb.dbo.sp_start_job #job_id=#JobId, #parameter_name=N'Email', #parameter_value=#VarValue;
Something like that.