In storprocedure how to set variable on where? - sql

CREATE PROCEDURE[BoardID]
#sParent varchar(8000)
AS
Select Boardid,PONO,ImageStatus
from BoardDetail
Where
Boardid=1 and #sParent
Why #sParent create error how to use this variable on where ......i want to supply string as parameter and it will be set on where ......like #sParent

It sounds like what you really want is to create a dynamic sql statement if that's what you want then try this:
Create Procedure [BoardID]
#sParent varchar(8000)
AS
Declare #SQL VarChar(8500)
SELECT #SQL = 'Select Boardid,PONO,ImageStatus from BoardDetail Where
Boardid=1 and '
SELECT #SQL = #SQL + #sParent
Exec ( #SQL)
GO

You need to set a field to your #sParent parameter in the WHERE clause:
...
WHERE
Boardid = 1 AND [fieldNameThatIsMatchingSParent] = #sParent
...
or similar.

If you want to pass where clause into your sp try this :
CREATE PROCEDURE[BoardID]
#sParent varchar(8000)
AS
DECLARE #sql ntext
SET #sql = 'Select Boardid,PONO,ImageStatus from BoardDetail Where Boardid=1'
IF (#sParent <> '')
BEGIN
SET #sql = #sql + ' and ' + #sParent
END
EXEC #sql

WHERE
((#Boardid is null and 1=1)
OR
(#Boardid is not null and #Boardid = SomeTbl.Boardid))
This WHERE clause allows us to have an optional SQL Parameter without having to resort to dynamically constructed SQL.
Hope that helps!

You can use #sParent in where in 2 ways (depending what you need)
where [FieldName] = #sParent
or
where [FieldName] Like #sParent

CREATE PROCEDURE[BoardID]
#sParent VARCHAR(8000)
AS
SELECT Boardid, PONO, ImageStatus
FROM BoardDetail
WHERE
Boardid = 1
AND ('0' != #sParent AND [ColumnName] LIKE #sParent)

Related

SQL Function for SumIf 2012 [duplicate]

This question already has an answer here:
Creating SumIf function in SQL Server 2012
(1 answer)
Closed 7 years ago.
I have the following sql function, but not running correctly, the intended returned value is the total
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create FUNCTION [dbo].[SumIf](#ColumnName [varchar](100), #Criteria [varchar](500))
RETURNS [decimal] AS
BEGIN
-- Declare the return variable here
DECLARE #Total Decimal
DECLARE #TableName Decimal
Select #Total = SUM(#ColumnName) from #TableName where #Criteria
RETURN #Total
END
the use syntax would be something like
Select dbo.sumif(fees.fee_amount, Fees.Fee_Code ='B01')
So the tablename would also need to be extracted from the columnname variable passed.
I don't think you will be able to implement your function that way. You're essentially trying to pass an expression to the function which I don't think is possible in SQL Server. You may be able to do it with dynamic SQL passing in strings but not as cleanly as you're hoping.
you need dynamic SQL to do this, but unfortunately you can't use dynamic SQL inside a UDF. try this-
DECLARE #ColumnName [nvarchar](100) = '' --fill in values here
DECLARE #TableName [nvarchar](100) = ''
DECLARE #Criteria [nvarchar](500) = ''
DECLARE #s nvarchar(max)
DECLARE #res bigint
set #s = 'SELECT #result = SUM(' + #ColumnName + ') from ' + #TableName + ' where ' + #Criteria
exec sp_executesql #s, N'#result OUTPUT', #result = #res OUTPUT
select #res
You are way on the wrong track. If you wanted to put sumif() in a select statement, it would need to be a user-defined aggregation function, rather than just a user-defined function. The fact that you've declared #TableName to be decimal and then use it in a from clause points to other issues.
So, my suggestion is that you just do this in-line:
select sum(case when <condition> then <columnname> else 0 end) as sumval
from <tablename>
If you wanted a programming block to put the data together, then use a stored procedure. Something like:
Create FUNCTION [dbo].SumIf(#ColumnName varchar(100),
#TableName varchar(255)
#Criteria varchar(500),
#Total Decimal OUTPUT)
) AS
BEGIN
DECLARE #sql nvarchar(max) = 'Select #Total = SUM(#ColumnName) from #TableName where #Criteria';
set #sql = replace(#sql, '#ColumnName', #ColumnName);
set #sql = replace(#sql, '#TableName', #TableName);
set #sql = replace(#sql, '#Criteria', #Criteria);
sp_execute_sql #sql, N'#total decimal output', #total = #total output;
END;

Can I pass column name as input parameter in SQL stored Procedure

create procedure sp_First
#columnname varchar
AS
begin
select #columnname from Table_1
end
exec sp_First 'sname'
My requirement is to pass column names as input parameters.
I tried like that but it gave wrong output.
So Help me
You can do this in a couple of ways.
One, is to build up the query yourself and execute it.
SET #sql = 'SELECT ' + #columnName + ' FROM yourTable'
sp_executesql #sql
If you opt for that method, be very certain to santise your input. Even if you know your application will only give 'real' column names, what if some-one finds a crack in your security and is able to execute the SP directly? Then they can execute just about anything they like. With dynamic SQL, always, always, validate the parameters.
Alternatively, you can write a CASE statement...
SELECT
CASE #columnName
WHEN 'Col1' THEN Col1
WHEN 'Col2' THEN Col2
ELSE NULL
END as selectedColumn
FROM
yourTable
This is a bit more long winded, but a whole lot more secure.
No. That would just select the parameter value. You would need to use dynamic sql.
In your procedure you would have the following:
DECLARE #sql nvarchar(max) = 'SELECT ' + #columnname + ' FROM Table_1';
exec sp_executesql #sql, N''
Try using dynamic SQL:
create procedure sp_First #columnname varchar
AS
begin
declare #sql nvarchar(4000);
set #sql='select ['+#columnname+'] from Table_1';
exec sp_executesql #sql
end
go
exec sp_First 'sname'
go
This is not possible. Either use dynamic SQL (dangerous) or a gigantic case expression (slow).
Create PROCEDURE USP_S_NameAvilability
(#Value VARCHAR(50)=null,
#TableName VARCHAR(50)=null,
#ColumnName VARCHAR(50)=null)
AS
BEGIN
DECLARE #cmd AS NVARCHAR(max)
SET #Value = ''''+#Value+ ''''
SET #cmd = N'SELECT * FROM ' + #TableName + ' WHERE ' + #ColumnName + ' = ' + #Value
EXEC(#cmd)
END
As i have tried one the answer, it is getting executed successfully but while running its not giving correct output, the above works well
You can pass the column name but you cannot use it in a sql statemnt like
Select #Columnname From Table
One could build a dynamic sql string and execute it like EXEC (#SQL)
For more information see this answer on dynamic sql.
Dynamic SQL Pros and Cons
As mentioned by MatBailie
This is much more safe since it is not a dynamic query and ther are lesser chances of sql injection . I Added one situation where you even want the where clause to be dynamic . XX YY are Columns names
CREATE PROCEDURE [dbo].[DASH_getTP_under_TP]
(
#fromColumnName varchar(10) ,
#toColumnName varchar(10) ,
#ID varchar(10)
)
as
begin
-- this is the column required for where clause
declare #colname varchar(50)
set #colname=case #fromUserType
when 'XX' then 'XX'
when 'YY' then 'YY'
end
select SelectedColumnId from (
select
case #toColumnName
when 'XX' then tablename.XX
when 'YY' then tablename.YY
end as SelectedColumnId,
From tablename
where
(case #fromUserType
when 'XX' then XX
when 'YY' then YY
end)= ISNULL(#ID , #colname)
) as tbl1 group by SelectedColumnId
end
First Run;
CREATE PROCEDURE sp_First #columnname NVARCHAR(128)--128 = SQL Server Maximum Column Name Length
AS
BEGIN
DECLARE #query NVARCHAR(MAX)
SET #query = 'SELECT ' + #columnname + ' FROM Table_1'
EXEC(#query)
END
Second Run;
EXEC sp_First 'COLUMN_Name'
Please Try with this.
I hope it will work for you.
Create Procedure Test
(
#Table VARCHAR(500),
#Column VARCHAR(100),
#Value VARCHAR(300)
)
AS
BEGIN
DECLARE #sql nvarchar(1000)
SET #sql = 'SELECT * FROM ' + #Table + ' WHERE ' + #Column + ' = ' + #Value
--SELECT #sql
exec (#sql)
END
-----execution----
/** Exec Test Products,IsDeposit,1 **/

Stored procedure: how to use column as an input

I'm trying to create a simple stored procedure to count the number of empty records in my database:
CREATE PROCEDURE dbo.cnt_empty
#col NVARCHAR(10)
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
SELECT COUNT(#col) AS cnt
FROM dbo.mytable
WHERE #col = ''
END
GO
EXECUTE dbo.cnt_empty #col = N'field1' -- nvarchar(10)
I returns 0 for all the columsn I tested. What is wrong with this procedure?
Your string is not being assessed as the column name, so you are actually running "where 'field1' = ''"
You need to do something like this
set #sql = 'select #cnt = COUNT(*) from [' + #tableSchema + '].[' + #tableName +
'] where [' + #columnName + '] is not null';
-- print #sql; --uncomment for debugging
exec sp_executesql #sql, N'#cnt bigint output', #cnt = #cnt output;
Look at http://blog.hoegaerden.be/2009/02/15/script-find-all-empty-columns-in-database/ for the full script.
By doing this, your SQL statement is treating the parameter like a string, not like the name of a column. Take a look at sp_executesql. That will help you build up a SQL string and execute it.
you are matching #col (i.e. 'field1') against empty (i.e. '') in your where clause - that will never return a row.
What you want to do is declare a variable like #sql VARCHAR(500)
Then do
SET #sql = 'SELECT COUNT('+#col+') AS cnt FROM dbo.mytable'
Then try use the built in sp called sp_Executesql
http://msdn.microsoft.com/en-us/library/ms188001.aspx
This is because you are selecting the count of the variable not the count of the column.
Take a look at this article: http://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/
Basically using EXEC statement or sp_executesql should be your choice.

SQL Linked Server query with Parameters

I need to select value from SQL Linked Server & get it to loacal variable
This is what I've written so far:
DECLARE #SQLQUERY AS VARCHAR(1000)
DECLARE #FINALQUERY AS VARCHAR(1000)
DECLARE #OutVal AS VARCHAR(10)
SET #SQLQUERY = 'SELECT Field1 FROM Table1 WHERE Field2=' + CAST(#var1 AS VARCHAR)
SET #FINALQUERY = 'SELECT #OutVal=Field1 FROM OPENQUERY(LINKEDSERVER,' + '''' + #SQLQUERY + '''' + ')'
EXEC(#finalQuery)
but this is wrong as it does not set the local variable(#OutVal).
Instead of exec, use sp_execute_sql with an output parameter:
exec sp_executesql #FinalQuery, N'#OutVal output', #OutVal = #OutVal out
Since sp_executesql expects nvarchar parameters, be sure to change the definition of #FinalQuery to nvarchar(max).
#OutVal in query string does not recognized as a variable. use a function or return table statement.

How to specify a table dynamically in a Stored Procedure

Thanks for the feedback, but I was hoping for help with an UPDATE command, not SELECT.
Can anyone help with the syntax for an UPDATE command?
I am passing a table name into a Stored Procedure but the SQL does not seem to recognize it.
DECLARE #userTable AS VARCHAR(200);
SET #userTable = #currTable
UPDATE #userTable
SET [lang_String] = #lang_String, [date_Changed] = #submitDate1
WHERE (ID = #ID)
#currTable is passed into the Stored Procedure. All tables names are built by design in code.
You can't, you need to build the entire SQL string and then execute it, like this for example:
DECLARE #sql nvarchar(4000)
SELECT #sql = ' SELECT col1, col2, col3 ' +
' FROM dbo.' + quotename(#tblname) +
' WHERE keycol = #key'
EXEC sp_executesql #sql, N'#key varchar(10)', #key
Got this to work quite easily....
#myTable varchar(150)
/* Comments:
*/
AS
SET NOCOUNT ON;
DECLARE #sql varchar(max);
SET #sql = 'SELECT [ID], [StringID], [GUID] FROM ' + #myTable + ' ORDER BY [GUID]';
print (#sql)
EXECUTE(#sql);
SET #langTable = Null;
FYI, the values available for myTable are stored in another table and are not available to users for edit. Table names are built dynamically in code based on a unique combination of values.