How to send column name as param in stored proc and function in MSSQL - sql

I'm trying to create a stored procedure in mssql (sql server) which takes the params of table name and column name. The stored proc should update given table and column name with base 64 value. I was able to create the function to convert string to base64 in sql server, which is a follows,
ALTER FUNCTION [dbo].[uFnStrToB64]
(
#InputString VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
RETURN (
SELECT
CAST(N'' AS XML).value(
'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
, 'VARCHAR(MAX)'
)
FROM (
SELECT CAST(#InputString AS VARBINARY(MAX)) AS bin
) AS RetVal
)
END;
Now, I'm calling this function in following stored procedure, as follows
ALTER PROCEDURE [dbo].[UpdateTableColumnWithB64]
#tbl sysname,
#Name sysname
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL NVARCHAR(MAX);
SET #SQL = N' UPDATE ' + QUOTENAME(#tbl)
+ N' SET ' + #Name + ' = ' + dbo.uFnStrToB64(#Name)
EXECUTE sp_executesql #SQL
END
But instead of updating the column value with base 64 of the column value, it is replacing it with base 64 of column name. But when I run following update command, it works flawlessly,
UPDATE mytable SET mycolumn=dbo.uFnStrToB64(mycolumn)
I'm calling stored proc as follows,
DECLARE #return_value int
EXEC #return_value = [dbo].[UpdateTableColumnWithB64]
#tbl = mytable,
#Name = mycolumn
SELECT 'Return Value' = #return_value
GO
Adding create and insert table commands, if someone wants to run it and try it,
CREATE TABLE mytable(
mycolumn varchar(max) NULL
);
INSERT INTO mytable(mycolumn) VALUES ('test'), ('test2'), ('test3');
Can somebody help me understand, when I move the update statement to stored procedure why the same update statement takes mycolumn as string instead of getting value from column? I'm open to change function and stored proc Or open for ways to do base 64 conversion in stored proc without usage of function.

Thanks to #dan, following is the solution
SET #SQL = N' UPDATE ' + QUOTENAME(#tbl)
+ N' SET ' + QUOTENAME(#Name)
+ N' = dbo.uFnStrToB64(' + QUOTENAME(#Name)
+ N');';

Related

Pass a table as parameter in openquery

I've created a datatype and declared a table of this type which I intend to pass as a parameter to an OPENQUERY statement. OPENQUERY returns an error that the object has no columns.
Firstly, the table parameter is defined as follows:
CREATE TYPE LooseTimecardsTableType AS TABLE ([LABORKEY] [float] NULL)
GO
DECLARE #DataTable AS LooseTimecardsTableType
INSERT INTO #DataTable
SELECT DISTINCT WOBase.LABORKEY
FROM Lab_WO_DataWH AS WOBase
left outer JOIN Lab_hrs_DataWH LabHrsWH ON LabHrsWH.WORKORDERLABORKEY = WOBase.LABORKEY
WHERE LabHrsWH.WORKORDERLABORKEY IS NULL AND WOBase.LABORKEY IS NOT NULL AND WOBase.LABORPRICE <> 0
The data table returns a single column of LABORKEY's which I want use to restrict the number of records from the OPENQUERY. This in turn is defined as follows:
DECLARE #SQLString NVARCHAR(500), #TableVariable LooseTimecardsTableType
SET #SQLString = N'SELECT * FROM OPENQUERY(Remoteserver, ''SELECT DISTINCT
DA.USERNAME, DA.WORKORDERLABORKEY, LB.PERFORMEDBY
FROM
REMOTE.WORKORDERDETAILAUDITS DA
JOIN REMOTE.WORKORDERLABORBASE LB ON LB.LABORKEY = DA.WORKORDERLABORKEY
JOIN #TableVariable ON #TableVariable.LABORKEY = LB.LABORKEY
WHERE DA.WORKORDERAUDITCATEGORY = 0'')'
EXECUTE sp_executesql #SQLString, N'#TableVariable LooseTimecardsTableType READONLY', #DataTable
Please assist in getting this to work
Instead of using a table variable you could turn the select statement that populates the table into a view using the where clause and then join the view to the table on the remote server.
The table variable cannot be passed as a parameter to OPENQUERY. As my table had only a single column I was able to convert it to a string and pass the string to OPENQUERY as a parameter. I did this within a procedure that accepts a table variable. After parsing the table to a string, the procedure also runs the OPENQUERY.
CREATE PROCEDURE PRM_LIST ( #TableVariable LooseTimecardsTableType READONLY)
AS
DECLARE
#LBKY_NVAR NVARCHAR(2500),
#POINTER INT,
#SQLString NVARCHAR(max)
SELECT #POINTER = MIN(LABORKEY) FROM #TableVariable
WHILE #POINTER IS NOT NULL
BEGIN
SET #LBKY_NVAR = IIF(#LBKY_NVAR IS NULL,'('+''''+ CONVERT(VARCHAR,#POINTER) + '''',
#LBKY_NVAR + ',' + ''''+ CONVERT(VARCHAR,#POINTER) + '''')
SELECT #POINTER = MIN(LABORKEY) FROM #TableVariable WHERE LABORKEY > #POINTER
END
SET #LBKY_NVAR = #LBKY_NVAR + ')'
SET #LBKY_NVAR = REPLACE(#LBKY_NVAR,'''','''''')
SET #SQLString =
N'SELECT * FROM OPENQUERY(REMOTE, ''SELECT DISTINCT
DA.USERNAME, DA.WORKORDERLABORKEY, LB.PERFORMEDBY
FROM
REMOTE.WORKORDERDETAILAUDITS DA
JOIN REMOTE.WORKORDERLABORBASE LB ON LB.LABORKEY = DA.WORKORDERLABORKEY
WHERE DA.WORKORDERAUDITCATEGORY = 0
AND LB.LABORKEY IN '+CAST(#LBKY_NVAR AS nvarchar(2500))+ N'
'')'
EXEC (#SQLString)
GO
The procedure call is:
EXECUTE PRM_LIST #DATATABLE

SQL Server - Convert SQL to Stored Procedure

Suppose I have the following structure to a set of tables in my SQL Server (2012) DB:
StartDate: Col1: Col2: .... Coln:
And, the way the DBA set up the database (have no control over that - I only have query access), all the tables with this structure that I'd want to query have, say, names beginning with MyTbl....
So, I would like to create a query that queries ALL these tables at once to get data for a specific StartDate and I've done it using the following SQL:
declare #t table(tablename varchar(50))
declare #sql varchar(max)
set #sql = ''
insert into #t
SELECT t.name AS table_name FROM sys.tables AS t
WHERE t.name LIKE 'MyTbl%'
select #sql = #sql + 'Select ''' + tablename + ''' as Table_Name, t.* From ' + tablename +
' t where StartDate = ''2015-01-01'' +
' union ' from #t
Select #sql = substring(#sql, 1, len(#sql) - 6)
exec(#sql)
In other words:
Find all tables in my DB with names beginning with MyTbl
Query each table for any data with StartDate = '2015-01-01`
Union all those queries together to get one big dataset result
The SQL works perfectly, but I'm getting quite stuck in creating a stored procedure from this query that can take in a parameter for StartDate and I don't know enough about stored procedures to do this correctly.
How could I convert this into a stored procedure that takes a date in for StartDate (to replace the ''2015-01-01'' in the query)?
Any help / guidance would be GREATLY appreciated!!!
THANKS!!!
I noticed you were not looping through each table .. here is something I had put together
CREATE PROCEDURE get_tabledata (#date DATE)
AS
BEGIN
DECLARE #t TABLE (
id INT IDENTITY(1, 1)
,tablename VARCHAR(50)
)
DECLARE #id INT
DECLARE #tablename VARCHAR(max)
DECLARE #sql VARCHAR(max)
SET #sql = ''
INSERT INTO #t
SELECT t.NAME AS table_name
FROM sys.tables AS t
WHERE t.NAME LIKE 'MyTbl%'
SET #id = ##ROWCOUNT
IF (#id > 0)
BEGIN
WHILE (#id > 0)
BEGIN
SET #tablename = (
SELECT tablename
FROM #t
WHERE id = #id
)
SELECT #sql = #sql + 'Select ' + #tablename + ''' as Table_Name, t.* From ' + #tablename + ' t where StartDate = ' + '' + convert(VARCHAR, #date) + ''
SET #sql = #sql + ' union'
Set #id = #id -1;
END
SELECT #sql = substring(#sql, 1, len(#sql) - 6)
END
EXEC (#sql)
END
While it can be a little dense if you're not used to the styling Microsoft uses on these pages, the best place to start would be the Create Procedure documentation on MSDN
https://msdn.microsoft.com/en-us/library/ms187926.aspx
That said, creating a stored procedure is pretty straight forward. Here's a really simple procedure that takes a #startDate parameter and then just returns it back. This is just to illustrate how and where you define your parameters
create procedure dbo.MyProcedure
-- put your input parameters here
#StartDate date
as
--put the body of your procedure (i.e. everything you've written in your OP) here
select #StartDate
go
YOu'll notice however that if you run this twice in a row, you get an error, because it tries to build the same procedure again. Another thing which can come in handy is adding some code before your procedure which will basically check to see if it already exists, and if it does, alter the procedure rather than just blindly re-create it.
This is a snippet from a template I use quite often which handles all of that logic for you. The simplest way to use this is press CTRL-SHIFT-M, which brings up a dialogue to replace all those tags with values you provide.
use [<Database Name, sysname,>]
go
if not exists (select 1
from sys.procedures with(nolock)
where name = '<Procedure Name, sysname,>'
and [schema_id] = schema_id('<Schema, sysname,dbo>')
and type = 'P'
)
exec ('create procedure [<Schema, sysname,dbo>].[<Procedure Name, sysname,>]
as
select ''Procedure not defined.'' as ErrorDescription
return')
--Executed as dynamic SQL since SQL Server Management Studio considures the straight SQL code a syntax error for some reason on the create procedure statement
GO
alter procedure [<Schema, sysname,dbo>].[<Procedure Name, sysname,>]
<Parm 1 Name, sysname,include [#]> <Parm 1 Datatype, sysname,><Parm 1 Default, sql_variant,include [=] if used>,
<Parm 2 Name, sysname,include [#]> <Parm 2 Datatype, sysname,><Parm 2 Default, sql_variant,include [=] if used>
as
/*******************************************************************************************************
********************************************************************************************************/
---------------------------------------------
-- declare variables
---------------------------------------------
---------------------------------------------
-- create temp tables
---------------------------------------------
---------------------------------------------
-- set session variables
---------------------------------------------
set nocount on
---------------------------------------------
-- body of stored procedure
---------------------------------------------
return

Passing two values to a stored procedure?

I've written a stored procedure which is called on a link which provides a date value every time and #cg is NULL that time to filter the result on a particular date.
DECLARE #return_value int
EXEC #return_value = [dbo].[Get_Mydata]
#cg = NULL,
#tosearch = '15-05-2014'
SELECT 'Return Value' = #return_value
GO
And after first execution of the stored procedure, it gives some results and using same stored procedure.
I need to filter result by passing below parameter so this time #cg is NOT NULL.
DECLARE #return_value int
EXEC #return_value = [dbo].[Get_Mydata]
#cg = 'CUSTOMER NAME',
#tosearch = 'manish'
SELECT 'Return Value' = #return_value
GO
I'm not able to figure how should I create a dynamic where clause and add it to existing query as well as how to pass value to same parameter which already been passed as date.
More like first getting results for a particular date and then applying like filter on that result. I cannot pass different parameter that's Front end developers requirement.
This is my stored procedure and table data here. http://sqlfiddle.com/#!3/bb917
create proc Get_Mydata
(
#cg varchar(50),
#tosearch varchar(50)
)
as
begin
set nocount on
declare #sqlquery nvarchar(max)
set #sqlquery = N'select q_no, trandate, cust_name from testsp where CONVERT(Date, trandate, 103) = CONVERT(Date, ''' + #tosearch + ''' ,103)';
create table #temp1
(
q_no int,
trandate datetime,
cust_name varchar(50)
)
insert into #temp1(q_no, trandate, cust_name)
exec (#sqlquery)
select * from #temp1 as T;
set nocount off
end
What I have understood is that you want stored procedure to filter results on Date column when you pass null to #cg param and you want to filter results on Cust_name when you pass string 'Cust_Name' to your #Cg Param.
It should be fairly simple, But in any case you do not need a temp table to get the results back its just an over kill of a fairly simple query.
I would do something like this....
Pass the column name to #ColumnName Parameter, and your value to #tosearch parameter. It will build the query depending on what values you pass.
Make sure when you pass a value(Column Name) to #ColumnName.
create proc Get_Mydata
(
#ColumnName varchar(50),
#tosearch varchar(50)
)
as
begin
set nocount on;
declare #sqlquery nvarchar(max);
set #sqlquery = N' select q_no, trandate, cust_name '
+ N' from testsp '
+ N' where ' + QUOTENAME(#ColumnName) + N' = '
+ CASE
WHEN #ColumnName = 'trandate'
THEN N' CAST(#tosearch AS DATE)'
WHEN #ColumnName = 'cust_name'
THEN N' #tosearch'
ELSE N'' END
EXECUTE sp_executesql #sqlquery
,N'#tosearch varchar(50)'
,#tosearch
set nocount off;
end

adding a table as parameter in a query string in a stored procedure

I have the following query :
ALTER procedure [dbo].[jk_insertAllLocation]
#locationTbl as locationTable readonly,
#TableName varchar(100)
as
declare #tbl as locationTable,#sql varchar(max)
begin
set #sql = 'insert into ' + #TableName +'(location_id,name,address,latitude,longitude,distance,state,sub_cat,id_cat,icon_link,checkinsCount,IDSearch)
select * from ' + #locationTbl
exec sp_executesql #sql
end
I need to pass a table and a table name as parameter and I need to insert in the table name (#TableName) passed as parameter all the data in the table (#locationTbl) passed as parameter
but I know that I cannot concatenate the table (#locationTbl) in the query ...
so how can I fix this?
You can use temp tables (Temporary tables section on link):
ALTER procedure [dbo].[jk_insertAllLocation]
#locationTbl as locationTable readonly,
#TableName varchar(100)
as
begin
declare #tbl as locationTable,#sql varchar(max)
if object_id('#_tmp_location_table') is not null drop table #_tmp_location_table
select * into #_tmp_location_table from #locationTbl
set #sql = 'insert into ' + #TableName + '(location_id,name,address,latitude,longitude,distance,state,sub_cat,id_cat,icon_link,checkinsCount,IDSearch) select * from #_tmp_location_table'
exec sp_executesql #sql
end

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.