Case statement inside trigger - asp.net

create trigger Insert_emp on dbo.emp
after insert
as
begin
declare #tablename varchar(50)
declare #rdatetime varchar(20)
declare #month int
set #rdatetime = (select Bdate from inserted)
set #month = (select datepart(mm,#rdatetime))
case when #month = 2 then set #tablename = 'FEP_EMP' end
print #tablename
end
Trigger will execute after,inserting record in emp table.It will pick up date which is inserted.From that date month will be calculated.I want set value of tablename.

CASE in SQL Server can only be used to get scalar values - it cannot be used to decide which code block or statement to execute. To handle conditional code execution, use the regular IF / ELSE statements.
Change your trigger to something like:
create trigger Insert_emp on dbo.emp
after insert
as
begin
declare #tablename varchar(50)
declare #rdatetime varchar(20)
declare #month int
set #rdatetime = (select Bdate from inserted)
set #month = (select datepart(mm,#rdatetime))
IF #month = 2
set #tablename = 'FEP_EMP'
print #tablename
end

Related

Like Does Not Work With Particular Sort of Stored Procedure

I have created a stored procedure that is using forms from ASP.NET to create a keyword search of thousands of books we have in our database.
The problem is that I have inherited code from another developer, and must use her code. I cannot rewrite the stored procedure.
As a result, I have to find a way to add the LIKE operator to the following part of the stored procedure:
Books = #Books OR #Books IS NULL
This is because the #Books is the part of the form where the user enters in a keyword search. I have looked up how to use the LIKE operator in a stored procedure, but nothing applies to this type of code.
The complete stored procedure is listed below:
Create Procedure spSearchAuthors
#FirstName nvarchar(100) = NULL,
#LastName nvarchar(100) = NULL,
#Books nvarchar(50) = NULL
As
Begin
Select FirstName, LastName, Books from Authors where
(FirstName = #FirstName OR #FirstName IS NULL) AND
(LastName = #LastName OR #LastName IS NULL) AND
(Books = #Books OR #Books IS NULL)
End
Go
A LIKE has simple syntax: %, _, [...]
In this case you could keep it simple.
By concatinating a % to both ends of the string variables.
CREATE Procedure spSearchAuthors
#FirstName NVARCHAR(100) = NULL,
#LastName NVARCHAR(100) = NULL,
#Books NVARCHAR(50) = NULL
AS
BEGIN
SELECT FirstName, LastName, Books
FROM Authors
WHERE (#FirstName IS NULL OR FirstName LIKE '%'+#FirstName+'%')
AND (#LastName IS NULL OR LastName LIKE '%'+#LastName+'%')
AND (#Books IS NULL OR Books LIKE '%'+#Books+'%');
END;
GO
Using Dynamic SQL is more complicated.
CREATE Procedure spSearchAuthors
#FirstName NVARCHAR(100) = NULL,
#LastName NVARCHAR(100) = NULL,
#Books NVARCHAR(50) = NULL
AS
BEGIN
DECLARE #DynSql NVARCHAR(800);
DECLARE #ParmDefinition NVARCHAR(100);
SET #DynSql = N'SELECT FirstName, LastName, Books FROM Authors';
IF #FirstName IS NOT NULL
BEGIN
SET #DynSql += CHAR(10)+'WHERE FirstName LIKE #FirstName';
SET #FirstName = N'%'+#FirstName+N'%';
END;
IF #LastName IS NOT NULL
BEGIN
IF #FirstName IS NULL
SET #DynSql += CHAR(10)+'WHERE ';
ELSE
SET #DynSql += CHAR(10)+'AND ';
SET #DynSql += 'LastName LIKE #LastName';
SET #LastName = N'%'+#LastName+N'%';
END;
IF #Books IS NOT NULL
BEGIN
IF #FirstName IS NULL AND #LastName IS NULL
SET #DynSql += CHAR(10)+'WHERE ';
ELSE
SET #DynSql += CHAR(10)+'AND ';
SET #DynSql += 'Books LIKE #Books';
SET #Books = N'%'+#Books+N'%';
END;
SET #ParmDefinition = N'#FirstName NVARCHAR(102), #LastName NVARCHAR(102), #Books NVARCHAR(52)';
EXECUTE sp_executesql #DynSql, #ParmDefinition,
#FirstName = #FirstName,
#LastName = #LastName,
#Books = #Books;
END;
GO

How do I get value of a column from select operation and use it in another select operation in a stored procedure?

ALTER PROCEDURE sp_GetLoginInformation
(
#userid INT OUTPUT,
#UserName NVARCHAR(50),
#Password NVARCHAR(50)
)
AS
BEGIN
IF EXISTS (SELECT #userid = UserId
FROM tblLoginInfo
WHERE UserName = #UserName COLLATE SQL_Latin1_General_CP1_CS_AS
AND Password = #Password COLLATE SQL_Latin1_General_CP1_CS_AS)
BEGIN
SELECT *
FROM tblUserInformation
WHERE UserId = #userid
END
END
Decalred a Variable #COL to use it in other Query.
Please check the modified procedure with comments.
ALTER PROCEDURE sp_GetLoginInformation ( #userid int output, #UserName nvarchar(50), #Password nvarchar(50) ) as
begin
------ VARIABLE TO STORE INFORMATION FROM SELECT STATEMENT
DECLARE #COL VARCHAR(50);
IF EXISTS (Select #userid=UserId from tblLoginInfo where UserName=#UserName COLLATE SQL_Latin1_General_CP1_CS_AS and Password=#Password COLLATE SQL_Latin1_General_CP1_CS_AS)
BEGIN
------ ASSIGNING THE VALUE IN DECLARED VAARIABLE THROUGH SELECT STATEMENT
Select #COL=Column_NAME from tblUserInformation where UserId=#userid;
END
------------------ USE OF THE DECALRED VARAIBLE IN OTHER QUERY -------------
SELECT * FROM SECOND_TABLE WHERE COLUMN_NAME = #COL;
END

How to get single output from PL/SQL procedure having select statement

I am trying to execute one PL/SQL procedure. I am getting nullpointerexception every time. Might be I am returning the procedure in wrong way.
Can you please help me in this procedure.
PROCEDURE p_regidexport(countryid IN varchar2, cropid IN varchar2, productid IN VARCHAR2, pregid out varchar)
IS
fnc VARCHAR2(30) := 'P_REGIDEXPORT';
query VARCHAR2(10000);
regid varchar(20);
BEGIN
select REG_ID into regid from GRS_Registration where LOC_ID =(select loc_id from GRS_location where Country = ' || countryid || ') AND CROP_ID = (select crop_id from GRS_crop where CROP_NM = ' || cropid || ')AND REG_NAME =' || '''' || productid || ''';
pregid := regid;
sub_log('P_REGIDEXPORT:'||pregid);
dbms_output.put_line(pregid);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No record present');
END P_REGIDEXPORT;
you need not to concatenate in parameter value. because its not dynamic query. so, you can directly pass the parameter variable into ur query.
make sure that your qry will return one single value.
its just idea based upon ur code, u can try based upon ur requirement.
Hope it will help you!!
create or replace PROCEDURE p_regidexport(countryid IN varchar2, cropid IN varchar2, productid IN VARCHAR2, pregid out varchar)
IS
fnc VARCHAR2(30) := 'P_REGIDEXPORT';
query VARCHAR2(10000);
regid varchar(20);
BEGIN
begin
select nvl(REG_ID,'0') into regid from GRS_Registration
where
LOC_ID =(select loc_id from GRS_location where Country = countryid ) AND
CROP_ID = (select crop_id from GRS_crop where CROP_NM = cropid)AND
REG_NAME = productid ;
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No record '); --- or regid ='0';
end;
pregid := regid;
--sub_log('P_REGIDEXPORT:'||pregid);
dbms_output.put_line(pregid);
EXCEPTION
WHEN others THEN
dbms_output.put_line('No record present' || ' - ' || sqlerrm);
END P_REGIDEXPORT;
All the best!! if it is useful click up button which is in left side of this answer

Stored Procedure not execute as expected

I have written following stored procedure
CREATE procedure [dbo].[findUSerID]
#Column_name varchar(50),
#TR_ID int
AS
DECLARE #sql nvarchar(max) = 'SELECT ' +#Column_name+ '
FROM Transfer_TB
WHERE TID =' + CAST(#TR_ID AS VARCHAR(10))
EXEC sp_executesql #sql
Table definition :
CREATE TABLE [dbo].[Transfer_TB]
(
[TID] [int] NULL,
[ABC] [varchar](20) NULL,
[XYZ] [varchar](50) NULL,
[LMN] [varchar](50) NULL,
[PQR] [varchar](50) NULL,
)
But it does not return the proper output.
Like I have called it from my asp page code for that using n tier architecture.
public string check_validID(string branch,int trId)
{
string user_Br_ID;
clsBranch_TB objbr = new clsBranch_TB();
clsUserTB objuser = new clsUserTB();
objuser.User_Branch = 'XYZ';
objuser.Extra_Int = 32;
DataSet ds = clsAdminLogic.findUSerID(objuser);
if (ds.Tables[0].Rows.Count == 0)
{
user_Br_ID = clsAdminLogic.getno_of_Emp(objbr);
}
else
{
user_Br_ID = ds.Tables[0].Rows[0][0].ToString();
}
return user_Br_ID;
}
public static DataSet findUSerID(clsUserTB objuser)
{
DataSet ds = DataAccessLayer.clsLogs.findUSerID(objuser);
return ds;
}
public static DataSet findUSerID(clsUserTB objuser)
{
SqlParameter[] param = {
new SqlParameter("#TR_ID",objuser.Extra_Int),
new SqlParameter("#Column_name",objuser.User_Branch)
};
DataSet ds = DataAccessLayer.SqlHelper.FillDataNewRJ(
DataAccessLayer.clsDataAccessLayer.con.ConnectionString.ToString(),
CommandType.StoredProcedure, "findUSerID", (param)
);
return ds;
}
As it executes it, there is value present in database, but still it enters into if part of that function.
Please help me and guide if something wrong in above code
Your stored procedure is prone to Sql-Injection. do the following to protect yourself against it.
CREATE procedure [dbo].[findUSerID]
#Column_name SYSNAME
,#TR_ID INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql nvarchar(max);
SET #sql = N' SELECT ' + QUOTENAME(#Column_name)
+ N' FROM Transfer_TB '
+ N' WHERE TID = #TR_ID '
exec sp_executesql #sql
,N'#TR_ID int'
,#TR_ID
END
If your Stored procedure is returning a scalar value "UserID" as the name suggest you should be doing something like......
CREATE procedure [dbo].[findUSerID]
#Column_name SYSNAME
,#TR_ID INT
,#UserID INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql nvarchar(max);
SET #sql = N' SELECT #UserID = ' + QUOTENAME(#Column_name)
+ N' FROM Transfer_TB '
+ N' WHERE TID = #TR_ID '
exec sp_executesql #sql
,N'#TR_ID int , #UserID INT OUTPUT'
,#TR_ID
,#UserID OUTPUT
END
there is value present in database, but still it enters into else part of that function
I assume this is the part you're talking about (there are 3 functions in that code)
if (ds.Tables[0].Rows.Count == 0)
{
user_Br_ID = clsAdminLogic.getno_of_Emp(objbr);
}
else
{
user_Br_ID = ds.Tables[0].Rows[0][0].ToString();
}
Yes. Your if goes into the else if the rows are not 0. It's doing exactly what its being told. That basic logic error is the least of your worries though. You're storing branches as columns?
i found solution for this problem, actually that particular record contains values instead of selective column that's why query returning the null value.
So i just have added one condition my stored procedure to fix it .
ALTER procedure [dbo].[findUSerID]
#Column_name varchar(50),
#TR_ID int
AS
DECLARE #sql nvarchar(max) = 'SELECT ' +#Column_name+ '
FROM Transfer_TB where TID =' + CAST(#TR_ID AS VARCHAR(10))+'
and '+#Column_name+'<> null'
exec sp_executesql #sql

How to check if username exists

How to return 1 if username exists and 0 in other case? Here is what I've tried.
IF EXISTS (SELECT * FROM [User] WHERE UserName = #UserName and EmailID=#EmailID)
begin
return 1;
end
else
begin
declare #CreatedOn datetime
select #CreatedOn = getdate()
insert into [User](UserName,Password,EmailID,ContactNo,CreatedOn) values(#UserName,#Password,#EmailID,#ContactNo,#CreatedOn)
CREATE PROCEDURE CheckUserExists
AS
#UserName NVARCHAR(MAX),
#Email NVARCHAR(MAX)
BEGIN
IF EXISTS (SELECT 1 FROM [User] WHERE UserName = #UserName OR EmailID=#EmailID)
BEGIN
RETURN 1
END
ELSE BEGIN
RETURN 0
END
END
Maybe you could try this query:
Select count(*) from [user] where UserName = #UserName and EmailID=#EmailID
and if user name exists count(*) will be larger then 0
I see a bigger problem here. you stated you want to know if the user exists or not. but the query shows a side affect, that if the user doesn't exist you will create the user in the same call. these should be separate sqlcommands. one for the query/reading and another for the command/insert.
to determine if the user exists a simple select 1 from [users] where [username] = #user should suffice. if any (1?) rows are returned the user exists, otherwise the user does not exist.
you can then issue the command to create the user
insert into [User](UserName,Password,EmailID,ContactNo,CreatedOn) values(#UserName,#Password,#EmailID,#ContactNo,getdate())
Try this:
IF EXISTS (SELECT 1 FROM [User] WHERE UserName = #UserName and EmailID=#EmailID)
begin
return 1;
end
else
return 0;
/* Execute the SP As*/
DECLARE #return_value int
EXEC #return_value = [dbo].[CheckUserExists]
Select #return_value
/*STORED PROCEDURE*/
CREATE PROCEDURE CheckUserExists
AS
#UserName NVARCHAR(MAX),
#Password NVARCHAR(MAX)
#EmailID NVARCHAR(MAX),
#ContactNo NVARCHAR(MAX)
BEGIN
IF EXISTS (SELECT 1 FROM [User] WHERE UserName = #UserName and EmailID=#EmailID)
BEGIN
RETURN 1;
END
ELSE
BEGIN
DECLARE #CreatedOn DATETIME
SELECT #CreatedOn = GETDATE()
INSERT INTO [User](UserName,Password,EmailID,ContactNo,CreatedOn)
VALUES(#UserName,#Password,#EmailID,#ContactNo,#CreatedOn)
RETURN 0;
END
CREATE PROCEDURE CheckUserExists
AS
#UserName NVARCHAR(MAX),
#Email NVARCHAR(MAX)
BEGIN
declare #usercount int
Select #usercount = count(UserName) from [user] where UserName = #UserName and EmailID=#EmailID
IF (#usercount = 1)
BEGIN
RETURN 1
END
ELSE BEGIN
RETURN 0
END
END

Resources