How to bind variables in stored procedure - snowflake-cloud-data-platform

I have created a stored procedure in snowflake with update command. I need to update a table.Below is the code
create or replace procedure sp1(col1 varchar,col2 varchar)
returns varchar not null
as
$$
begin
execute immediate 'update emp set first_name ='||:col1 || 'where' ||:col2|| 'between 1 and 5';
end;
$$;
I am getting the below error
call('bob','id');
Syntax error:ENT_ERROR' on line 3 at position 3 : SQL compilation error: (line 28)
syntax error line 1 at position 51 unexpected '1'. (line 28)
Please help me on this issue.

You should include single-quotes for the varchar value and be careful about the spaces. This one should work:
create or replace procedure sp1(col1 varchar,col2 varchar)
returns varchar not null
as
$$
begin
execute immediate 'update emp set first_name = ''' || :col1 || ''' where ' || :col2 || ' between 1 and 5';
end;
$$;

Try this:
create or replace procedure sp1(col1 varchar,col2 varchar)
returns varchar not null
as
$$
begin
execute immediate 'update emp set first_name =' + col1 + ' where '+ col2 +
'between 1 and 5';
end;
$$;

Related

Need help in dynamic procedure

I have a start date and end date so how to use both in place of getdate()
I have a code in which if the date interval between start and end date is less than 30 than it should show the start and end date. Instead it is showing error-
Explicit conversion from data type int to date is not allowed.
I am notusing int anywhere but still it is showing I have tried convert in argument passing and other things but its not stopping showing error.
My code is-
if object_id('ias_test_SCHEMA.week2','p') is not null
drop procedure ias_test_SCHEMA.week2;
go
create procedure ias_test_SCHEMA.week2(#startdate date,#enddate date)
as
BEGIN
declare #datediff integer,
#res varchar(30);
set #datediff = DATEDIFF(day, #startdate, #enddate);
if #datediff<=30
begin
declare #stmt nvarchar(max),
#stmt1 nvarchar(max);
set #stmt= N'SELECT #res=(DATENAME(DAY,convert(date,'+convert(nvarchar(20),#startdate)+')) + '' '' + DATENAME(MONTH,convert(date,'+convert(nvarchar(20),#startdate)+')) + '' '' + DATENAME(YEAR,convert(date,'+convert(nvarchar(20),#startdate)+')))';
Execute sp_executesql #stmt, N'#res varchar output',
#res=#res output;
print 'The date is:' + #res;
set #stmt1= N'SELECT DATENAME(DAY,convert(date,'+convert(nvarchar(20),#enddate)+')) + '' '' + DATENAME(MONTH,convert(date,'+convert(nvarchar(20),#enddate)+')) + '' '' + DATENAME(YEAR,convert(date,'+convert(nvarchar(20),#enddate)+'))';
Execute sp_executesql #stmt1;
end;
end;
go
and I am executing it by line-
execute ias_test_SCHEMA.week2 '2015-10-03','2015-10-08';
but it is showing compiled successfully but at the time of result is not showing error. I am stuck here!
Please can anyone help me through it? Thank you!
these are the commands produced by your code:
SELECT #res=(DATENAME(DAY,convert(date,2015-10-03)) + ' ' + DATENAME(MONTH,convert(date,2015-10-03)) + ' ' + DATENAME(YEAR,convert(date,2015-10-03)))
SELECT DATENAME(DAY,convert(date,2015-10-08)) + ' ' + DATENAME(MONTH,convert(date,2015-10-08)) + ' ' + DATENAME(YEAR,convert(date,2015-10-08))
the issue is in the missing quotes around the dates inside the convert built in the dynamic string.
if you run:
select convert(date,2015-10-03);
you get:
Msg 529, Level 16, State 2, Line 1 Explicit conversion from data type
int to date is not allowed.
the following command can be executed successfully:
select convert(date,'2015-10-03');
the solution is to add escaped single quotes when building the dynamic query:
set #stmt= N'SELECT #res=(DATENAME(DAY,convert(date,'''+convert(nvarchar(20),#startdate)+''')) + '' '' + DATENAME(MONTH,convert(date,'''+convert(nvarchar(20),#startdate)+''')) + '' '' + DATENAME(YEAR,convert(date,'''+convert(nvarchar(20),#startdate)+''')))';

How to write a sql query for different conditions in where clause on demand?

I have to pass different parameters as columns from code behind, so i written 15 gridview binding methods for 15 columns, so to avoid this i like to set in query.For example if my column 1 then pick this where clause and if column 2 then pick this where clause.So how to write like this?
Here is an example of how you would create and run dynamic queries
CREATE PROCEDURE sp_search
#param1 int = NULL,
#param2 int = NULL
AS
BEGIN
DECLARE #query_string nvarchar(4000);
SET #query_string = 'SELECT * FROM TABLE_NAME WHERE 1 = 1 ';
IF(#param1 IS NOT NULL)
BEGIN
SET #query_string = #query_string + ' AND columnName1 = ' + CAST(#param1 AS VARCHAR);
END
IF(#param2 IS NOT NULL)
BEGIN
SET #query_string = #query_string + ' AND columnName2 = ' + CAST(#param2 AS VARCHAR);
END
EXEC sys.sp_executesql #query_string;
END

creating dynamic query in variable

I am creating a dynamic query in sql server 2005 stored procedure and I am getting error if
dates are sent empty/null to the stored procedure that:
This input parameter cannot be converted
So, how to check in Stored procedure that covert only id date is not empty:
below is my query. I have checked the null in if condition but then also it is showing me error
If #startDate IS NOT NULL AND #endDate is Not null
Begin
set #strCondition = ' FO.Rf_Date >= convert(datetime, ''' + Convert(varchar,#startDate,112) + ''') and FO.Rf_Date<= convert(datetime, ''' + Convert(varchar,#endDate,112) + ''')'
End
If they can be empty or null you need to also exclude the empty variables, E.g.
IF NULLIF(#startDate, '') IS NOT NULL AND NULLIF(#endDate, '') IS NOT NULL
You can also make use of ISDATE() Function along with CASE statement something like this..
SET #strCondition = N' SELECT * FROM TableName WHERE 1 = 1 ' --<-- 1 = 1 so you can append any more line starting with 'AND'
+ CASE WHEN ISDATE(NULLIF(#startDate,'')) = 1
THEN N' AND FO.Rf_Date >= convert(datetime, ''' + Convert(varchar,#startDate,112) + ''') '
ELSE N'' END
+ CASE WHEN ISDATE(NULLIF(#endDate,'')) = 1
THEN N' AND FO.Rf_Date <= convert(datetime, ''' + Convert(varchar,#endDate,112) + ''')'
ELSE N'' END
Note
ISDATE() function returns 0 if the passed parameter isnt date value, It also returns 0 is the passed value is NULL.

update procedure error syntax near '='

I simple want to update the price with for example here 3, but this with a stored procedure.
I already tried it with normal syntax:
update tblPrijs
set PrijsVerkoop = PrijsVerkoop + 1
where PrijsId = '6';
and this works fine.
But my stored procedure always returns :
updatetblPrijssetPrijsVerkoop=PrijsVerkoop+3.00wherePrijsId=11
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '='.
and I don't know what I did wrong..
The stored procedure:
alter PROCEDURE updatePrice
-- Add the parameters for the stored procedure here
#table nvarchar(50),
#field nvarchar(50),
#increase nvarchar(50),
#id nvarchar(50),
#value nvarchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare #sql as nvarchar(400);
-- Insert statements for procedure here
set #sql = 'update' + #table + 'set' + #field + '=' + #field + '+' + #increase +
'where' + #id + '=' + #value
print #sql /* drukt het resultaat van concat af */
exec(#sql)
END
GO
This is what I write in my query:
updatePrice'tblPrijs', 'PrijsVerkoop','3.00', 'PrijsId','11'
sorry for the dutch names of fields and tables...
I think it is something small and obvious that is wrong but I just can't see it..
This is in SQL Server 2012
Thank you in advance!
You need to add some spaces in there.
This:
set #sql = 'update' + #table + 'set' +#field + '=' ...
if you add the following parameters:
#table = SomeTable
#field = SomeField
will result in this sql:
updateSomeTablesetSomeField=
Surely that's not what you intended.
I'm assuming by the print #sql statement that you wanted to print your sql statement before executing it. What did it show?
Here's something to try:
set #sql = 'update ' + #table + ' set ' + #field + ' = ' + #field + ' + ' + #increase + ' where ' + #id + ' = ' + #value
I added spaces inside each string, at the start and at the end. Some of those spaces are not strictly needed, but they won't change the outcome either.

SQL Server: executing dynamic/inline sql table name within EXEC and passing geometry as geometry parameter

I'm trying to execute an inline SQL statement within a stored procedure. I'm working with SQL Server 2008.
The problem is that I can't execute the first inline statement (with WHERE clause). It crashes because the string within EXEC(...) is dynamically created and all concatenated variables must be of type varchar.
Error that appears when calling procedure:
An expression of non-boolean type specified in a context where a
condition is expected, near 'ORDER'.
The procedure looks like:
CREATE PROCEDURE loadMyRows
#table_name nvarchar(50),
#bounding_box varchar(8000)
AS
BEGIN
-- *********************************** COMMENT *********************************
-- ** This two code lines are correct and will return true (1) or false (0), **
-- ** but they doesn't work within inline EXEC(...) **
--DECLARE #bb geometry = geometry::STGeomFromText(#bounding_box, 4326);
--select TOP(5) wkt.STWithin(#bb) AS 'bool'
-- *********************************** COMMENT *********************************
IF #bounding_box <> ''
BEGIN
DECLARE #bb geometry = geometry::STGeomFromText(#bounding_box, 4326);
EXEC(
'SELECT TOP (' + #row_limit + ') * ' +
'FROM ' + #real_table_name + ' ' +
'WHERE wkt.STWithin('+#bb+') ' + -- <-- doesn't work :-(
-- 'WHERE wkt.STWithin(geometry::STGeomFromText('''+#bounding_box+''', 4326)) ' +
-- ^^ doesn't work, too :-(
'ORDER BY id ASC '
);
END
ELSE
BEGIN
EXEC(
'SELECT TOP (' + #row_limit + ') * ' +
'FROM ' + #real_table_name + ' ' +
'ORDER BY id ASC'
);
END
END
I've found a working solution for this problem. The way the MSDN showed me was http://msdn.microsoft.com/en-US/library/ms175170.aspx. There's written:
[...] the string is executed as its own self-contained batch.
That let me know, if I want to execute a dynamic statement with a table variable as string, it's the same as I would execute the query without the EXECUTE command, like:
SELECT TOP(#row_limit) *
FROM #real_table_name
WHERE ...
ORDER BY id ASC;
And this would probably not work for the table name.
So, if I write instead:
DECLARE #sql_statement nvarchar(MAX) = 'SELECT TOP(#limit) *
FROM ' + #real_table_name + '
ORDER BY id ASC';
-- declaration of parameters for above sql
DECLARE #sql_param_def nvarchar(MAX) = '#limit int';
EXECUTE sp_executesql #sql_statement, #sql_param_def, #limit = #row_limit;
Then, this would work. This is because I define the #sql_statement simply as a concatenated string which will just resolve the dynamic table name at runtime to a string with the name of the real existing table. The #limit parameter is untouched and is still a parameter.
If we then execute the batch we only must pass a value for the #limit parameter and it works!
For the geometry parameter it works in the same way:
DECLARE #bb geometry = geometry::STGeomFromText(#bounding_box, 4326);
SET #sql_statement = 'SELECT TOP(#limit) *
FROM ' + #real_table_name + '
WHERE wkt.STWithin(#geobb) = 1
ORDER BY id ASC';
-- NOTE: This ' = 1' must be set to avoid my above described error (STWithin doesn't return a BOOLEAN!!)
-- declaration of parameters for above sql
SET #sql_param_def = '#limit int, #geobb geometry';
EXECUTE sp_executesql #sql_statement, #sql_param_def, #limit = #row_limit, #geobb = #bb;
Hope this was clear ;-)
create proc usp_insert_Proc_Into_temp
#tempTable nvarchar(10) output
as
begin
set #tempTable = '##temp'
declare #query nvarchar(200)
--Select statement
set #query = 'select 1 as A,2 as B, 3 as C into'+ ' '+#tempTable+''
exec(#query)
end
go
declare #tempTable nvarchar(10)
exec usp_insert_Proc_Into_temp #tempTable output
exec('select * from' + ' '+ #tempTable+'')
exec ('drop table'+ ' '+#tempTable+'')

Resources