Table variable in a stored procedure - sql

I would like to create a simple stored procedure which take as a parameter existing tables.
I thought this procedure should work:
#UserID INT,
#TableName varchar(255)
AS
BEGIN
IF(#UserID is not null)
BEGIN
update t
set t.ProductID = 100
from dbo.[#TableName] t
END
When I execute this stored procedure with a table name, the query completed with errors:
Invalid object name 'dbo.#TableName'.
Any advice?

You'd have to do something like the following:
DECLARE #SQL NVARCHAR(100)
SET #SQL = 'UPDATE ' + #TABLENAME + ' SET t.ProductID = 100 '
EXEC sp_executesql #SQL
Note: You have no WHERE clause so all items in the #TableName will be updated.

Related

Passing Parameters to Create a View in SQL Server using stored procedure - dynamic SQL

I am trying to create views using stored procedure and passing dynamic SQL in SQL Server.
ALTER PROCEDURE sp_businessUnit_totalRequests
(#ViewName AS VARCHAR(50),
#RequiredBU AS VARCHAR(50))
AS
BEGIN
DECLARE #Req_View_Name AS SYSNAME;
DECLARE #sql NVARCHAR(MAX);
SET #Req_View_Name = #ViewName
SET #sql = '
CREATE VIEW [Req_View_Name]
As
BEGIN
Select [Reviewer], Count([Reviewer]) as Total_Requests From [dbo].[reviews_not_sent] where [BU] = #RequiredBU Group By [Reviewer];
END
'
SET #sql = REPLACE(#sql, '[Req_View_Name]', QUOTENAME(#Req_View_Name));
EXEC sp_executesql #sql,
N'#RequiredBU VARCHAR(50)',#RequiredBU=#RequiredBU
END;
EXEC sp_businessUnit_totalRequests 'Annuities_Requests', 'Annuities';
The stored procedure gets created. But when I tried to execute the stored procedure, it says:
Incorrect Syntax near View
This code should work:
ALTER PROCEDURE [dbo].[sp_businessUnit_totalRequests]
(
#ViewName AS VARCHAR(50),
#RequiredBU AS VARCHAR(50)
)
AS
BEGIN
Declare #Req_View_Name AS SYSNAME;
DECLARE #sql NVARCHAR(MAX);
Set #Req_View_Name = #ViewName
set #sql = '
CREATE VIEW [Req_View_Name]
As
Select [Reviewer], Count([Reviewer]) as Total_Requests From [dbo].[reviews_not_sent] where [BU] = ''' + #RequiredBU + ''' Group By [Reviewer];
'
SET #sql = REPLACE(#sql, '[Req_View_Name]', QUOTENAME(#Req_View_Name));
EXEC sp_executesql #sql
END;
This Code works although it suffers from SQL Injection. Parametrized SQL View creation is not possible.

How to get all columns of a table,whereas TableName is a Output Paramater?

I want a stored procedure to display all the columns of it but I would select table name externally like EXEC spDisplay 'tblName'.. I want Table name as a output parameter...How can I do that?
Use dynamic SQL, like below..
create proc spDisplay
#TableName as varchar(100)
as
Begin
exec('select top 10 * from '+#TableName)
End
Below is the SP, It will take Table Name as Input Parameter.
CREATE PROCEDURE MySp
#TableName VARCHAR(MAX)
AS
BEGIN
DECLARE #Sql VARCHAR(MAX)
SET #Sql = 'SELECT * FROM ' + #TableName
EXEC(#Sql)
END
Below is the query to execute above Sp, Here emp is my table name
EXEC MySp 'emp'

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.