I want to make a Stored Procedure that has a minimum of 2 required parameters, but that it can also be called with 2,3,4,5... and so on parameters. The Reason: I have multiple tables that have Key-Value pairs, but then this Key-Value can be a group to another list of Key-Value pairs. So that the first one is the parent key to the next list. This is an example of 2 Tables that can be called with the same procedure, which is detailed afterwards:
--MyListTableAlpha
+- Key1 (ValueA)
+- Key2 (ValueB)
+- Key3 (ValueC)
+- Key4 (ValueD)
--MyListTableBravo
+- Parent Uno
+- Key1 (Value1A)
+- Key2 (Value1B)
+- Parent Dos
+- Key1 (Value2A)
+- Key2 (Value2B)
+- Key3 (Value3C)
The code has to be for SQL Server 2008.
This is what I have for the 2 paremeter Stored Procedure:
CREATE PROCEDURE [dbo].[SPListValue]
-- Add the parameters for the stored procedure here
@listName nvarchar(100) = null,
@keyVal nvarchar(100) = null
-- optional parameters go here?!?
AS
BEGIN
SET NOCOUNT ON;
SELECT [value_string] from [tablenames]
JOIN [keyvalues] on [tablenames].[id] = [keyvalues].[tableid]
WHERE [dbo].[keyvalues].[key] = @keyVal
END
Table [keyvalues]
has the columns: id
,tableid
,parentkeyid
,key
,value
. Where parentkeyid
is used when the values are grouped to know which one they belong to.
This is how I would like to call MyListTableAlpha
from my Java code (notice 2 ?s):
CallableStatement cs1 = conn1.prepareCall("{call SPListValue(?,?}"); //notice 2 ?s
cs1.setString(1, "MyListTableAlpha");
cs1.setString(2, "Key1");
ResultSet rs1 = cs1.executeQuery();
rs1.next();
value = rs1.getString("value_string"); // Prints ValueA
This is how I would like to call MyListTableBravo
from my Java code (notice 3 ?s):
CallableStatement cs1 = conn1.prepareCall("{call SPListValue(?,?,?}"); //notice 3 ?s
cs1.setString(1, "MyListTableBravo");
cs1.setString(2, "Parent Uno");
cs1.setString(3, "Key2");
ResultSet rs1 = cs1.executeQuery();
rs1.next();
value = rs1.getString("value_string"); // Prints Value1B