the name is not a valid identifier error in function - sql-server-2008

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

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.

Must declare the scalar variable in my procedure

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.

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.

When getting maxid from table name

Declare #Id bigint
EXEC procGetMaxNumber #Id output,'employee'
I'm getting an error message
Error converting data type varchar to bigint
when I execute the procedure with the above parameters
-- =============================================
-- Description: <Fetches Max Id for a particular table>
-- =============================================
CREATE PROCEDURE [dbo].[procGetMaxNumber]
(
#Id BIGINT OUTPUT,
#TblName nvarchar(50)
)
AS
BEGIN
SET NOCOUNT ON;
Declare #Query nvarchar(max) = ''
set #Query = 'SELECT ' + #Id + ' = isnull(Max(Id),0)+ 1 from ' + #TblName
--print #Query
Exec (#Query)
END
This looks extremely dangerous to me. What exactly are you going to do with the "next" Id value once you get it? You know that immediately after you retrieve this value, someone could insert a row and take it (or even fail to insert a row, and still take it even if the transaction rolled back), right? If you want to reserve an Id value and be sure that is the number you get, just run the insert, don't do any of this max+1 to insert later.
Anyway you can't use EXEC to retrieve an output parameter from dynamic SQL, you'll need to use sp_executesql:
DECLARE #query NVARCHAR(MAX) = N'SELECT #Id = COALESCE(MAX(Id),0)+1
FROM dbo.' + QUOTENAME(#TblName) + ';';
EXEC sp_executesql #query, N'#Id INT OUTPUT', #Id OUTPUT;

Stored procedure with table name as parameter

I have a stored procedure, and I would like to assign the number of rows of that table to a variable and later use that variable.
I am calling the procedure like:
EXEC TEST.dbo.myProc nameOfTable
The procedure is something like:
CREATE PROCEDURE myProc #table_name varchar(1024) AS
BEGIN
DECLARE #Nval INT
/* SOME INSTRUCTIONS */
SELECT #Nval = COUNT(*) FROM #table_name
END
When executing I am getting an error:
Msg 156, Level 15, State 1, Procedure nLQ, Line 57
Incorrect syntax near the keyword 'FROM'.
How would I assign the variable #Nval?
You can't parameterise a table name like that, FROM #table_name. Only way is to execute dynamic TSQL.
Before you do that, read: The Curse and Blessings of Dynamic SQL
try this
ALTER PROCEDURE [dbo].[sp_tablenametest]
#table_name varchar(50),
#PMId int,
#ValueEq int
AS
BEGIN
SET NOCOUNT ON;
DECLARE #cmd AS NVARCHAR(max)
SET #cmd = N'SELECT * FROM ' + #table_name +
' WHERE Column1 = ''' + #PMId + '''' +
' AND Column2= ''' + #ValueEq + ''''
EXEC sp_executesql #cmd
END