Put Where Clause in a parameter - sql

I would like to use a where clause in a parameter. I already tried the following code but it doesnt work. the last line us red underlined, i reckon that i have to bind the parameter to the select command somehow. Would be great if anyone could help me with it.
Begin
declare #name varchar(MAX)
declare #x int
Set #x = 1
If #x = 1
BEGIN
SET #name = 'WHERE Username = Frank'
END
ELSE
BEGIN
SET #name = ''
END
END
now use it in:
SELECT * FROM dbo.person #name

Here is a typical way to have optional parameters in a query:
declare #UserName varchar(255) = 'Frank'
select *
from person p
where (#UserName is null or UserName = #UserName)
If you set the variable to NULL then all users are chosen. If you set it to a value, then only that user is chosen.

Looks like you want an optional Stored Procedure parameter to either pull rows with the parameter value or pull all rows:
CREATE PROCEDURE foo
#name AS VARCHAR(MAX) = NULL
AS
BEGIN
SELECT * FROM dbo.person WHERE Username = #name OR #name IS NULL
END
GO

Related

Procedure to rename a list of procedure, only renames the last procedure in the list

I created a procedure where I could pass a list of procedure names separated by a comma, and then I would like to rename all the procedures from the list by adding a custom suffix in the end.
But I am facing an issue where it would only rename the last item from the list and ignore all the rest. I don't know why it would not rename each one from table variable list since I am calling sp_rename on each item in the list.
Also, I was able to print each loop with raiseerror()
Here's the complete procedure that I written.
CREATE PROCEDURE [dbo].[Util_ProcRename]
#ProcNameListWithComma VARCHAR(MAX)
AS
BEGIN
DECLARE #ID INT
SET #ID = 1;
DECLARE #oldname varchar(200)
DECLARE #newname varchar(200);
DECLARE #NOTUSED VARCHAR(20)
SET #NOTUSED = '_NOTUSED_'+REPLACE(CONVERT(varchar(20), GETDATE(), 101),'/','')
DECLARE #ProList AS TABLE (
ID INT IDENTITY,
ProcName VARCHAR(200),
NewProcName VARCHAR(200)
);
--Get proc names from a list into a table with ID to use in While loop
INSERT INTO #ProList (ProcName)
SELECT P AS ProcName
FROM dbo.SplitText(#ProcNameListWithComma,',')
WHILE (#id <= (SELECT MAX(ID) FROM #ProList))
BEGIN
SET #oldname = (SELECT ProcName FROM #ProList WHERE ID = #ID)
SET #newname = #oldname + #NOTUSED
EXEC p_rename #oldname, #newname
SET #ID = #ID + 1
END
UPDATE p
SET NewProcName = p.ProcName+#NOTUSED
FROM #ProList p
WHERE ID = ID
--TO see the list that got renamed
SELECT
a.Name AS [NewName],
a.type
FROM
dbo.sysobjects a
WHERE
name IN (SELECT NewProcName FROM #ProList)
END
GO
Despite the indentation, you are doing the update after the loop. So, it is only called once.
Move the END to after the UPDATE.

Parameter in LIKE statement only returning exact values

I have a parameterized query shown below that is supposed to return info about items that have a name like the parameter. However, it only works for exact matches
BEGIN
SET NOCOUNT ON
DECLARE #name varchar(50)
SET #name = 'bananas'
SELECT category, sum(netweight) AS NetWeight from PieChart group by
category, name HAVING name LIKE #name
END
Since 'bananas' is in the database, it returns that info. If it put 'banan', it returns nothing.
Thanks for your help!
You can also put the wildcards in the WHERE clause:
BEGIN
SET NOCOUNT ON;
DECLARE #name VARCHAR(50) = 'bananas';
SELECT category ,
SUM(netweight) AS NetWeight
FROM PieChart
WHERE [name] LIKE '%' + #name + '%'
GROUP BY category ,
[name]
END
You need wildcards. In addition, you should use where, not having. So:
BEGIN
SET NOCOUNT ON
DECLARE #name varchar(50);
SET #name = 'banan%';
SELECT category, sum(netweight) AS NetWeight
FROM PieChart
WHERE name LIKE #name
GROUP BY category, name;
END;

how to set two Variable with one select in sql

i have two Variable type in t-sql and want set they in sql. i use this code:
DECLARE #Id int
DECLARE #Name nvarchar(100)
set #Id, #Name = (Select Id, Name From Member Where username = #username)
but this not working, and i not want use this code:
set #Id = (Select Id From Member Where username = #username)
set #Name = (Select Name From Member Where username = #username)
i have use one select.
Here's the right syntax for what you want to do:
DECLARE #Id int
DECLARE #Name nvarchar(100)
SELECT #Id = Id, #Name = Name
From Member
Where username = #username

Select and Set not working together in TSQL FUNCTION

I am using a function in SQL SERVER and setting a user variable using select and after that set . But seems set is not working .
--#id is input
Declare #result varchar(MAX)
SELECT #result = INFO FROM USER_INFO WHERE ID= +''+'DOMAIN\'+#id+''
IF #result IS NULL
SET #result = 'DOMAIN\'+#id+''
return (#result)
If user is not found I want to select id not the null values. Buts seems it coming null always
Set is not working in conditional statement.
What I am doing wrong?
Below is the update:
yes Slippery, I checked its coming null. If I set
SET #result ='MY ID'
it works but #result = 'DOMAIN\'+#id did not work
The whole function
FUNCTION [dbo].[USER_INFO]
(
-- Add the parameters for the function here
#id varchar(300)
)
RETURNS varchar(MAX)
AS
BEGIN
Declare #result varchar(MAX)
SELECT #result = INFO FROM USER_INFO WHERE ID= +''+'DOMAIN\'+#id+''
IF #result IS NULL
SET #result = 'DOMAIN\'+#id+''
return (#result)
END
Just in case that really is the entire function, you'll need that first line to be "CREATE FUNCTION" (or "ALTER FUNCTION" if it already exists), instead of just "FUNCTION"...
This will eliminate NULL's from being returned by your function:
DECLARE #result VARCHAR(MAX)
-- Eliminate NULL being passed in so string concatenation doesn't return NULL
IF #id IS NULL
SET #id = ''
-- Set the output value...if nothing exists, set it to 'x'
SET #result = (SELECT TOP 1 ISNULL(INFO,'x') FROM USER_INFO WHERE ID = 'DOMAIN\' + #id);
-- Now, neither #result OR #id will be NULL so the following should always return something other than NULL
IF #result = 'x'
SET #result = 'DOMAIN\' + #id
RETURN (#result)
Based on the other comments, try this:
Declare #result varchar(MAX)
SELECT #result = INFO FROM USER_INFO WHERE ID= 'DOMAIN\'+#id
IF #result IS NULL
SET #result = 'DOMAIN\'+ ISNULL(#id, '')
return (#result)
I don't think you need all that handing with the quotes and pluses
You should try like this. No need of those extra '' single quotes at end
Declare #result varchar(MAX)
SELECT #result = INFO FROM USER_INFO WHERE ID= 'DOMAIN\' + #id
IF #result IS NULL
SET #result = 'DOMAIN\' + #id
return (#result)
Few points to mention: your function name and the table name both are same user_info. Try naming them differently like
FUNCTION [dbo].[Get_USER_INFO]
(
-- Add the parameters for the function here
#id varchar(300)
)
SELECT #result = INFO FROM USER_INFO
Also, you should call your function like
select dbo.Get_USER_INFO('my-user_id')
The difference between select and set is that if set didn't found any value then it will return null but if select didn't found any value then it will show the previous value of the variable, the same case is happening for you when the #result value is null select don't assign any value and return the same previous value instead of assigning null and that is the reason the if statement is false and its not moving to the Set statement.
koppinjo, if the #result variable never set to anything then it should hit the block, but i guess the first time the #result variable value is not null so it's not hitting the block.
please view this for post more clarification.
http://www.mssqltips.com/sqlservertip/1888/when-to-use-set-vs-select-when-assigning-values-to-variables-in-sql-server/

procedure that returns varchar

I tried to make a function that returns varchar, but I can't because I'm using CREATE TABLE inside, and when I'm creating it with a procedure I can't return a value.
I wanted to know if you have some advice.
I made this just to make a string with emails separated by ";" so I can have all the "manager" mails in one varchar (for the recipients).
ALTER procedure [dbo].[Manager_email]
AS
BEGIN
declare #mails varchar (max),
#number_of_mails int,
#counter int
set #counter=2
create table #temp ( id int identity, email varchar(30))
insert into #temp (email)
select Email
from hr.Employees
where lower (EmpRole) like 'manager'
set #number_of_mails=##ROWCOUNT
set #mails = (select email from #temp where id =1 ) + ';'
while #counter <= #number_of_mails
BEGIN
set #mails = #mails + (select email from #temp where id =#counter ) + ';'
set #counter = #counter+1
END
drop table #temp
return cast (#mails as varchar (200))
END
You can only return integer value back from the procedure, If you want to return varchar value from procedure its good to make use of output variable in procedure.
Example
CREATE PROCEDURE Sales.uspGetEmployeeSalesYTD
#SalesPerson nvarchar(50),
#SalesYTD money OUTPUT
AS
SET NOCOUNT ON;
SELECT #SalesYTD = SalesYTD
FROM Sales.SalesPerson AS sp
JOIN HumanResources.vEmployee AS e ON e.BusinessEntityID = sp.BusinessEntityID
WHERE LastName = #SalesPerson;
RETURN
like in above procedure return #SalesYTD from procedure.
you can check full post on MSDN : Returning Data by Using OUTPUT Parameters
You can use function instead
CREATE FUNCTION Manager_email ()
RETURNS varchar(max)
AS
BEGIN
declare #email varchar(30)
declare #emails varchar(max)
set #emails = ''
declare cur cursor for
select Email
from hr.Employees
where lower (EmpRole) like 'manager'
open cur
fetch next from cur into #email
while ##fetch_status = 0
begin
set #emails = #emails + #email + ';'
fetch next from cur into #email
end
close cur
deallocate cur
return #emails
END
You can use table variable instead of temporary table. In that case you can continue to use UDF.