Stored procedure - Multiple string parameters with IN clause sql - asp.net

i want to filter the rows using Stored procedure. below is my query
Create PROCEDURE [dbo].[Test]
#SearchTerm VARCHAR(100)
AS
BEGIN
Select * from master where name in (#SearchTerm)
END
In code behind,
cmd.Parameters.AddWithValue("#SearchTerm", "peter")
when i run with above parameter, it's work fine.
but when i pass like this
cmd.Parameters.AddWithValue("#SearchTerm", "'peter','rahul'")
this time no rows fetching.
i tried manually then also it's not working.
exec Test ''peter','rahul''
Please help me, how to pass muliple string Using IN clause?

One method is
Create PROCEDURE [dbo].[Test]
#SearchTerm VARCHAR(100)
AS
BEGIN
Select * from master where ','+#SearchTerm+',' like '%,'+name+',%'
You can find more methods at http://www.sommarskog.se/arrays-in-sql-2008.html

Related

How to execute MariaDB stored procedure from azure data factory?

I wanted to 'Call' MariaDB Procedure from Azure Data Factory.
How can this be achieved, are there any other service which can be integrated with ADF to call this MariaDB procedures
I tried calling the procedure by writing the query using lookup activity.
It fails while showing this error.
ErrorCode=InvalidParameter,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=The value of the property 'columns' is invalid: 'Value cannot be null.
Parameter name: columns'.,Source=,''Type=System.ArgumentNullException,Message=Value cannot be null.
Parameter name: columns,Source=Microsoft.DataTransfer.Common,'
Lookup activity reads and returns the content of the query. I tried to repro this by creating three stored procedures in Azure SQL database for Maria DB.
First Stored procedure is written to update the data in the table.
DELIMITER $$
CREATE PROCEDURE update_inventory()
BEGIN
UPDATE inventory SET quantity = 150
WHERE id = 1;
END$$
DELIMITER ;
When this procedure is called in ADF lookup activity, error occurs.
Second stored procedure is written with select query.
DELIMITER $$
CREATE PROCEDURE select_inventory()
BEGIN
select * from inventory;
END$$
DELIMITER ;
When this SP is called, ADF pipeline is executed successfully.
In order to execute the stored procedure with update statements (or any statements), a select statement is added in the Stored procedure.
DELIMITER $$
CREATE PROCEDURE update_select_inventory()
BEGIN
UPDATE inventory SET quantity = 150
WHERE id = 1;
select * from inventory;
END$$
DELIMITER ;
When this stored procedure is called through Lookup activity, it got executed successfully.
Try adding select statement in the stored procedure and execute it in Lookup activity. Or add Select statement after Call stored procedure statement.
By selecting the 'query' option, you can call the stored procedure using lookup activity. From your error message, it looks like you are missing the parameter columns while calling the stored procedure.
Did you try executing the same code using the client tools like MySQL workbench? If you can execute the stored proc from other client tools, then you should be able to execute the same using the lookup activity.
I tested from my end and was able to execute the Stored procedure using lookup activity. Please see the below screenshot for your reference.

Stored procedure does not create new table

I am trying to create tables dynamically in a SQL Server database.
Like this with input from a textbox:
ALTER PROCEDURE [dbo].[opretNyEsyn]
#Navn NVARCHAR(100)
AS
BEGIN
DECLARE #SQLString NVARCHAR(MAX)
SET #SQLString = 'create table ' + QUOTENAME(#Navn) +
'([EsynNummer][int]Identity(1,1),
[Dato][datetime])'
END
But nothing happens when I run the method from the form, the table isn't created, and I get no errors.
What am I missing?
Notice. This is just a test table. It isn't supposed to look like this in the end.
Thanks in advance
You are just creating the statement, but in order to create the tables, you need to Execute the statement using the EXEC statement of sp_executesql SP. Add an execute statement to your Procedure. Like this
ALTER PROCEDURE [dbo].[opretNyEsyn]
#Navn nvarchar(100)
as
Begin
declare #SQLString nvarchar(max)
set #SQLString = 'create table ' + QUOTENAME(#Navn)+
'([EsynNummer][int]Identity(1,1),
[Dato][datetime])'
exec(#SQLString)-- Execute the Statement
End
Go
You need to execute dynamic SQL:
ALTER PROCEDURE [dbo].[opretNyEsyn]
#Navn SYSNAME
as
Begin
declare #SQLString nvarchar(max);
set #SQLString = 'create table ' + QUOTENAME(#Navn)+
'([EsynNummer][int]Identity(1,1),
[Dato][datetime])';
EXECUTE (#SQLString);
End;
Anyway I recommend to read The Curse and Blessings of Dynamic SQL and Packaging Permissions in Stored Procedures:
CREATE TABLE #tbl
The desire here is to create a table of which the name is determined at run-time.
If we just look at the arguments against using dynamic SQL in stored procedures, few of them are really applicable here. If a stored procedure has a static CREATE TABLE in it, the user who runs the procedure must have permissions to create tables, so dynamic SQL will not change anything. Plan caching obviously has nothing to do with it. Etc.
Nevertheless: Why? Why would you want to do this? If you are creating tables on the fly in your application, you have missed some fundamentals about database design. In a relational database, the set of tables and columns are supposed to be constant. They may change with the installation of new versions, but not during run-time.

Casting a String to a Symbol in PLSQL

I've created an anonymous PLSQL block to test and I'm running into an issue with the formatting.
set serveroutput ON
BEGIN
FOR I IN (SELECT DISTINCT do.SUBOBJECT_NAME from dba_objects do WHERE do.object_name='MY_TABLE' AND do.OBJECT_TYPE='TABLE PARTITION') LOOP
dbms_output.put_line(I.subobject_name);
SELECT
t.field
INTO
some_var
FROM
MY_TABLE PARTITION(I.subobject_name) t;
END LOOP;
END;
However I get several compilation errors, which I believe are related to the fact that I.subobject_name is a string. I believe the PARTITION function wants an actual partition symbol(proper term for this?), but I can't give it in this loop.
Is there any kind of casting function that can perform what I'm looking for?
Partition IS NOT A FUNCTION. Partition is keyword
In your context your whole statement is static , thus you CANNOT pass partition name into it; partition name must be specified at compile time.
You can re-create your statement dynamically and then pass partition name in the loop -
a-la you are doing it. Just make sure you will concatenate string and not use bind variables, or your statement at run time won't be parsed and won't run.
Name for the symbol is table partition

Get a parameter's name

I want to get a parameter's name in plsql.
For example,
procedure sp_example(myParam in varchar2) is
paramName varchar2(30);
begin
paramName = 'myParam';
end
end procedure sp_example;
Is there a way to get the name of myParam using reflection, instead of hard coding it?
Try:
select argument_name from all_arguments where object_name = 'SP_EXAMPLE';
This view can also show you the data types, positions, etc., and you can use it in SQL or PL/SQL. Plenty of info in the various metadata views.
If you want to get the names of parameters retrieved in their respective positions, use
select argument_name from user_arguments where object_name='SAMPLE_PROC' order by position;

Passing parameter to IN SQL statement

I collected some values to be looked up from a DB column inside a string variable and was trying to pass this as a parameter in the SQL StoredProcedure.
ALTER PROCEDURE [dbo].[InkDB]
(
#ser nvarchar(255),
#svt nvarchar(255)
)
AS
SELECT DISTINCT Details from tbData WHERE (Name IN #svt AND Address=#ser)
This gives me a syntax error near #svt message while trying to run the query.
From my webpage, the parameter has value something like ('PersonA', 'Person B', 'Person C') that is being passed. How do I use the IN statement in this case?
I would do it with XML. Could not find this solution in the duplicate question so I add it here.
Your SP could look like this:
alter procedure InkDB
#ser nvarchar(255),
#svt xml
as
declare #T table
(
Name nvarchar(50)
)
insert into #T
select T.N.value('.', 'nvarchar(50)')
from #svt.nodes('/N') as T(N)
select distinct Details
from tbData
where Name in (select Name from #T) and
Address=#ser
And you would call it like this.
exec InkDB '', '<N>PersonA</N><N>PersonB</N>'
Dynamic Query
Alter procedure test
(
#ser nvarchar(255),
#svt nvarchar(255)
)
AS
BEGIN
declare #sql nvarchar(Max)
Set #sql='SELECT DISTINCT semester_code from mst_paper WHERE course_code IN ('+#svt+') AND branch_code='+#ser+''
exec sp_executesql #sql
END
Its a common mistake - you are passing a single value (expression) of type string to IN operator but IN expects a comma delimited list of values (expressions) and not a single string variable.
What you need to do here is to have a function that would split the given parameter into a multiple values based on given delimiter and then use that list with IN keyword. For example,
SELECT DISTINCT Details from tbData WHERE Name IN (SELECT Val FROM dbo.efn_Split(#svt, ',')) AND Address=#ser
where efn_Split is a table value function that will split comma-separated values into a table. See these various SO questions for implementation of such function:
Split function equivalent in T-SQL?
How to split string using delimiter char using T-SQL?
Yet another alternative is to construct the SQL statement and execute with sp_executesql.
IN needs to be as follows:
... IN (#param1, #param2, ...)
So, you should do:
SELECT DISTINCT Details from tbData WHERE Name IN (#svt) AND Address=#ser
Update:
The alter procedure statement you provided in your question is syntactically incorrect. My answer provides the correct syntax for writing the statement and it compiles.
Reading your question over again, I see you have in fact have two issues. The first was a syntax error and the second passing in a comma delimited list in a single parameter.
The answer is you simply cannot provided a comma delimited list of values at runtime into a single string type parameter that is used in the IN (...) clause. Now, on this second point, I would argue that this is not a good design/programming approach to the problem, but it can be done using dynamic SQL or parsing out each value from the string parameter, store them into a temp table then revise your query to join to that, or use a (or use a table valued function and store the parsed items there, where it can be queried from.
Below is the corrected syntax for your code, but it would not solve the second aspect of passing in a string containing a comma delimited list of values. That could be solved as I described above.
For the syntax error, first, you can create a dummy table to test your code. Note, a typical database table should have a primary key. This is strictly a dummy table to test the statement:
CREATE TABLE TbData(
Name nvarchar(255),
Details nvarchar(255),
Address nvarchar(255)
);
Then, you can create the initial stored procedure:
CREATE PROCEDURE Test
(
#ser nvarchar(255),
#svt nvarchar(255)
)
AS
BEGIN
SELECT DISTINCT Details FROM tbData WHERE Name IN (#ser) AND Address = #svt
END
And finally, execute the alter stored procedure statement you had asked about:
ALTER PROCEDURE Test
(
#ser nvarchar(255),
#svt nvarchar(255)
)
AS
BEGIN
SELECT DISTINCT Details FROM tbData WHERE Name IN (#ser) AND Address = #svt
END

Resources