Must declare the scalar variable in my procedure - sql-server-2008

Im trying to get return form below store procedure but this is not giving me value
can you please say what i am doing mistake in my procedure.
ALTER PROCEDURE CALCWEIGHT1
#EQUATION varchar(255),
#VOLUME decimal(10,2)
AS
BEGIN
declare #SQL varchar(max);
declare #WEIGHT decimal(10,2);
IF(#EQUATION = '') or(#EQUATION is null)
BEGIN
set #EQUATION =' SELECT #WEIGHT = (('+Convert(varchar(10),#VOLUME)+' / 1728.0 * 8.907 *100.0) / 100.0)'
END
else
BEGIN
set #SQL='SELECT #EQUATION= REPLACE('''+#EQUATION+''', ''VOLUME'', '''+Convert(varchar(10),#VOLUME)+''')'
exec #SQL
set #EQUATION='SELECT #WEIGHT= '+#EQUATION+' '
END
execute (#EQUATION)
END
for check i am execute with this value
EXEC CALCWEIGHT1 '',789
Thanks For your comments.

You are just assigning variables. You don't really select anything.
Remove your use of #Weight.

Related

How to Update values in sql by Muliple Column name in Sql

I want add values to multiple columns
ALTER PROCEDURE DynamicInsertQuery
#ColumnName VARCHAR(MAX),
#RiD VARCHAR(50)
AS
BEGIN
DECLARE #DynamicQuery NVARCHAR(MAX)
SET #DynamicQuery = 'UPDATE tbl_route_info SET ('+ #ColumnName +') = (1) WHERE RouteId=('+#RiD+')'
EXEC(#DynamicQuery)
END
This is the code I tried.
I run this procedure like this
DynamicInsertQuery '(1,2)','10'
I suspect you want something like this:
ALTER PROCEDURE DynamicInsertQuery (
#ColumnName VARCHAR(MAX),
#RiD VARCHAR(50)
) AS
BEGIN
DECLARE #DynamicQuery NVARCHAR(MAX);
SET #DynamicQuery = 'update tbl_route_into set #ColumnName = 1 where RouteId = #RiD';
SET #DynamicQuery = REPLACE(#DynamicQuery, '#ColumnName', #ColumnName);
EXEC sp_executesql #DynamicQuery, N'#RiD VARCHAR(50)', #RiD = #RiD;
END;
Notes:
You have too many parentheses in your version.
If you are learning to use dynamic SQL, then learn sp_executesql -- and how to use it to pass parameters.
You cannot pass names of things (columns, tables, etc.) as parameters, so that has to be placed directly in the string.
You can pass values into the string, such as #RiD.

Mysql - How to split text variable in stored procedure

I have a MySQL variable as below.
DECLARE str TEXT DEFAULT '2014-01-02 13:00:00|2014-02-04 12:59:59#0#2014-02-04 13:00:00|2014-03-04 12:59:59#0#2014-03-04 13:00:00|2014-04-02 13:59:59#0#2014-04-02 14:00:00|2014-05-02 14:59:59#0#2014-05-02 15:00:00|2014-06-03 14:59:59';
I want to break this whole string first by using the separator #0# and from the results break the string using separator |.
I have tried MySQL split_str function but I am not able to do it.
Its giving me the error split_str does not exist.
Please suggest some other way to do this.
Finally i have resolved my problem using below procedure.
I am able to solve it using temporary table and procedure. I am no more using mysql variable for this. We can call the procedure as below....
CALL SplitString('2014-01-02 13:00:00|2014-02-04 12:59:59#0#2014-02-04 13:00:00|2014-03-04 12:59:59#0#2014-03-04 13:00:00|2014-04-02 13:59:59#0#2014-04-02 14:00:00|2014-05-02 14:59:59#0#2014-05-02 15:00:00|2014-06-03 14:59:59', '#0#', 'tblindex');
Here tblindex is temporary table i have used.
My procedure is below....
DELIMITER $$
DROP PROCEDURE IF EXISTS `SplitString`$$
CREATE PROCEDURE `SplitString`( IN input TEXT,IN delm VARCHAR(10),tblnm varchar(50))
BEGIN
DECLARE cur_position INT DEFAULT 1 ;
DECLARE remainder TEXT;
DECLARE cur_string VARCHAR(1000);
DECLARE delm_length TINYINT UNSIGNED;
set #sql_drop = concat("DROP TABLE IF EXISTS ",tblnm);
prepare st_drop from #sql_drop;
execute st_drop;
set #sql_create = concat("CREATE TEMPORARY TABLE ",tblnm," (value VARCHAR(2000) NOT NULL ) ENGINE=MEMORY;");
prepare st_create from #sql_create;
execute st_create;
SET remainder = input;
SET delm_length = CHAR_LENGTH(delm);
WHILE CHAR_LENGTH(remainder) > 0 AND cur_position > 0
DO
SET cur_position = INSTR(remainder, delm);
IF cur_position = 0 THEN
SET cur_string = remainder;
ELSE
SET cur_string = LEFT(remainder, cur_position - 1);
END IF;
-- select cur_string;
IF TRIM(cur_string) != '' THEN
set #sql_insert = concat("INSERT INTO ",tblnm," VALUES ('",cur_string,"');");
prepare st_insert from #sql_insert;
execute st_insert;
END IF;
SET remainder = SUBSTRING(remainder, cur_position + delm_length);
END WHILE;
END$$
DELIMITER ;

the name is not a valid identifier error in function

Create FUNCTION [dbo].[fngetname]
(
#OrganisationID int=null,
#UserID int=null,
#ClientTypeID int
)
RETURNS varchar(500)
BEGIN
DECLARE #Name VARCHAR(500)
DECLARE #dbName VARCHAR(500)
set #dbName=(select ClientDataBase from dbo.ClientType where ClientTypeID=#ClientTypeID)
begin
set #Name='select UserName from ['+ #dbName+'].dbo.Users where UserID='+convert(varchar,#UserID)
exec #Name
end
return #Name
end
There are two issues here, first if you want to execute dynamic sql, you need to encapsulate your statement variable in parenthesises:
you need to add parenthesises to the exec #Name in your function declaration.
The function gets written but cannot execute it stops at the exec
replace that exec #Name with exec (#Name)
you can easily reproduce this error by just trying two simple lines (ofc replace the table and db-name with something you have ;)):
DECLARE #statement VARCHAR(MAX) = 'SELECT * FROM [nana].dbo.Fruits'
exec #statement
This should throw the exact same error.
Then add () around the #statement and it will work.
The second issue is, that you cannot use dynamic sql in a function, because they have to be deterministic (look here).
To get around this, rewrite that function behaviour into a stored procedure and then it should work ;).
One way to rewrite your function into a procedure might look like this(untested, because I do not have your database structure set up):
CREATE PROCEDURE spGetName #OrganisationID INT = NULL, #UserID INT = NULL, #ClientTypeID INT
AS
BEGIN
DECLARE #Name VARCHAR(500)
DECLARE #dbName VARCHAR(500)
SET #dbName = (SELECT ClientDataBase FROM dbo.ClientType WHERE ClientTypeID = #ClientTypeID)
SET #Name = 'select UserName from [' + #dbName + '].dbo.Users where UserID=' + CONVERT(VARCHAR, #UserID)
exec(#Name)
END
GO
Try using
exec sp_executesql #statement

Not getting id of newly created row using SCOPE_IDENTITY()

I have a stored procedure in which i am creating an insert statement in a string and then executing the statement.
When i am using SCOPE_IDENTITY() to retrieve the id of newly inserted record it is returning NULL.
Please check the code below -
ALTER PROCEDURE [dbo].[sgi_sp_SaveCompComponent]
-- Add the parameters for the stored procedure here
#Id int output,
#ComponentName nvarchar(50),
#VehicleSystemId nvarchar(10),
#NamingConvension nvarchar(50),
#IsSubcomponent bit=0,
#SubComponentId int=null,
#CompanyID int = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
Declare #TableName nvarchar(100) ='C'+ cast(#CompanyID as nvarchar(10)) +'_Components',
#AssociatedTable nvarchar(100)='C'+cast(#CompanyID as nvarchar(10))+'_'+ +REPLACE(#ComponentName,' ','');
DECLARE #cmd AS NVARCHAR(max)
-- Insert statements for procedure here
Set #cmd='insert into '+#TableName+ '( ComponentName, VehicleSystemId, NamingConvension, IsSubcomponent, SubComponentId, AssociatedTable) values(''';
set #cmd = #cmd + #ComponentName+''','''+ #VehicleSystemId+''','''+#NamingConvension+ ''','''+cast(#IsSubcomponent as nvarchar(10));
if (#SubComponentId is null)
set #cmd = #cmd +''',NULL,'''+#AssociatedTable +''')';
else
set #cmd = #cmd +''','''+cast(#SubComponentId as nvarchar(10))+''','''+#AssociatedTable +''');';
print (#cmd)
exec (#cmd)
set #Id=SCOPE_IDENTITY();
print (#Id)
END
Can anybody help me out resolve this issue
Thanks for sharing your valuable time.

Column name set in stored procedure but not working

Column name set in stored procedure but not working. But when I run this script empty rows appears. What I do this for run this script?
Create Procedure Test
()
AS
BEGIN
Declare #columnName nvarchar(50);
set #columnName ='StoreName';
SELECT *
FROM testtable
WHERE #columnName = 'storemanager'
END
You need to use dynamic SQL because you can't reference a column with a variable - T-SQL just doesn't parse things in that order. Try something like:
CREATE PROCEDURE dbo.Test
#columnName NVARCHAR(50),
#value NVARCHAR(4000)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'SELECT * FROM dbo.testtable WHERE '
+ QUOTENAME(#columnName) + ' = #value;';
EXEC sp_executesql #sql, N'#value NVARCHAR(4000)', #value;
END
GO
QUOTENAME() wraps the column in [square brackets] and hopefully protects you from SQL injection. You should also read these posts:
Bad habits to kick : using SELECT * / omitting the column list
Bad habits to kick : avoiding the schema prefix
My stored procedure "best practices" checklist