sql server parameter size overloading - sql

i am calling a stored procedure from my ASP.NET application. the stored procedure takes one parameter. the value that i am providing from my WEB Form is too large that it did not fully loading in variable of sql server. the data type of my sql server parameter is nvarchar(max) and the data type in my ASP.NET application is string.
the stored procedure is as below
Create procedure p_getProducts
#nm_emp nvarchar(max)
AS
BEGIN
select * from tblProduct where nm_user in(convert(nvarchar(max),#nm_emp));
END
please tell me which sql server data type i should use to overcome this problem.
Thanks.

For what I could suppose from your code, you should work with dynamic-sql and not using directly the parameter as value for the IN clause. Try with this proc.
Create procedure p_getProducts
#nm_emp nvarchar(max)
AS
BEGIN
DECLARE #SQL NVARCHAR(MAX);
SELECT #SQL = N'select * from tblProduct where nm_user in(' +
#nm_emp + N')'
EXEC sp_executeSQL #SQL

Related

how to pass table name as parameter to sql table valued function?

I want to pass the table name as a parameter to table_valued function in MS SQL Server
CREATE FUNCTION maxid
(
-- Add the parameters for the function here
#tblname sysname,
#feild nvarchar(max),
)
RETURNS TABLE
AS
RETURN
(
-- Add the SELECT statement with parameter references here
select ISNULL(max(#feild),0)+1 from #tblname
)
You cannot use dynamic SQL in table valued or any other TSQL function. However, the code you provide seems to be used to obtain the next value of some identifier or counter field. The way you want to do it is highly deprecated and leads to concurrency problems.
Indeed, SQL Server can do it using at least two standard methods:
using a sequences
creating an identity column
I have done it but with store procedure
CREATE procedure [dbo].[get_maxid]
#tblname nvarchar(max),
#col nvarchar(max)
as
Begin
declare #sql nvarchar(max);
set #sql='select ISNULL(MAX('+#col+'),0)+1 as id from '+ QUOTENAME( #tblname)
execute sp_executesql #sql
End
Now Execute Store Procedure
exec get_maxid #col='col_name',#tblname='tbl_name'

Scalar variable must be declared in SQL variable

I'm creating a report using sql scripts through management studio and I'm getting the error " Must Declare the scalar variable "#Account". I've been reading other similar questions on this portal but they are related to c#
I'm currently trying to reduce the code on the script so I decided to put a sql script into a variable because depending on a condition the where condition will change. Below is an example of the code
Declare #Account int = 1 , #SQL varchar(max)=''
Select #SQL = N'Select ColumnA,ColumnB, ColumnC from Table1 where ColumnA =1'
if #Account IS NULL
Begin
exec(#SQL)
end
--Here is where the error is hapening
else
begin
--This is the line causing the error
Select #SQL = #SQL + 'AND ColumnB=#Account"
exec(#SQL)
end
If I type manually the value of the variable next to "ColumnB=" it works but the account number will be selected by the user executing the script. I'm thinking on maybe building a temp table to capture the variable value and then do a sub query on the where condition but maybe the solution to this error may be more easier
You want sp_executesql:
select #SQL = #SQL + 'AND ColumnB=#Account';
exec sp_executesql #SQL, N'#Account int', #Account=#Account;
This is how you pass parameters into a dynamic SQL statement in SQL Server. I strongly recommend that you only use sp_executesql to execute SQL statements -- even when you don't have parameters. Using it makes it easy to implement parameters when you need them.
You are passing in '#Account' into the #SQL variable -- the underlying EXEC cannot see that variable.
One way of fixing this would instead be to do this:
Select #SQL = #SQL + 'AND ColumnB=' + CAST(#Account as varchar)

Dynamically get all parameter values in stored procedure

Is there any way to get all parameter values from a stored procedure dynamically?
In other words, iterate through all parameters in one stored procedure to get their values into one string. This is for a unified logging process for a bunch of stored procedures.
I can get the names of parameters:
SELECT PARAMETER_NAME
FROM INFORMATION_SCHEMA.PARAMETER
WHERE SPECIFIC_NAME = 'procedure_name';
Also, I tried to use dynamic SQL commands. I've generated a command with included parameter, but EXEC can't execute command.
#cmd = 'SELECT '#UserID' + CONVERT(NVARCHAR(MAX), #UserID)
+ '#Date' + CONVERT(NVARCHAR(MAX), #Date)'
EXEC #cmd
Is there any way to do this besides manually generating a list of parameter values for each stored procedure?
Since SQL Server 2014 there is sys.dm_exec_input_buffer a table valued function with an output column event_info that gives the full execution statement (including parameters).
I use this for error logging in stored procedures.
For example:
--include this inside the stored procedure
declare #statement nvarchar(max)
select #statement = event_info
from sys.dm_exec_input_buffer(##spid, current_request_id())
--this will print whatever you called the procedure with (including parameters)
print #statement
-- if you want to parse just the parameters from the statement, it can be done like this
declare #proc_name varchar(128) = object_name(##procid)
declare #param_idx int = charindex(#proc_name, #statement) + len(#proc_name)
declare #param_len int = len(#statement) - #param_idx
declare #params nvarchar(max) = right(#statement, #param_len)
select #params

Store result of dynamic SQL generating XML to XML Variable

So I have found plenty of examples across SO that show how to assign the result of dynamic SQL to variables but I have yet to find one that does it the way that I am trying to... So either I am going about this the wrong way or I just haven't found the proper syntax to perform this correctly.
Basically, I am trying to create an XML record of a row from a table before deleting the row from the table (think of it as an audit of the table) using a Stored Procedure. I was attempting to do this through dynamic SQL so that the Stored Procedure can be called from multiple other Stored Procedures that perform Delete operations on their corresponding tables, but before doing so they pass the necessary information (the #sql variable which will contain the select statement to obtain the record) to this Audit Stored Procedure.
Create Procedure dbo.AuditDelete(
#sql NVARCHAR(200),
#TableName VARCHAR(50),
#UserName NVARCHAR(256)
)
AS
DECLARE #XML XML
BEGIN
--at this point #sql will contain a select statement written by the calling stored procedure
--which is specifically written to return the record that is being deleted, example:
#sql = select * from my.table where tableId = 1 FOR XML AUTO
execute sp_executesql #sql, N'#XML XML OUTPUT', #XML = XML OUTPUT;
SELECT #XML
--I was doing this as a check to ensure that XML has the record
--because the execute command returned the XML record, but #XML is null...
--and I can't figure out why
--code for inserting into the Audit table
So I'm sure that its either some syntax I'm missing or perhaps I'm just going about this the wrong way. Any suggestions?
Note: this is being done in SSMS on SQL Server 2008 R2
You need to assign the result your query to the parameter in the dynamic SQL.
set #sql = N'set #XML = (select * from my.table where tableId = 1 FOR XML AUTO)'
execute sp_executesql #sql, N'#XML XML OUTPUT', #XML OUTPUT

SQL: Select dynamic column name based on variable

I have a Microsoft SQL stored procedure whose column name I want to set via a variable that is passed into it:
CREATE PROCEDURE [My_Procedure]
#myDynamicColumn varchar(50)
AS BEGIN
SELECT 'value' AS #myDynamicColumn
END
This does not work ("Incorrect syntax"). If I wrap the column name with [ ]:
SELECT 'value' AS [#myDynamicColumn]
The column name literally outputs as '#myDynamicColumn' instead of the actual value. Is there any way to do this? I've looked into dynamic SQL articles but nothing is quite what I'm asking for.
EXEC ('SELECT ''value'' AS ' + #myDynamicColumn)
You could build your query into a string and use exec
CREATE PROCEDURE [My_Procedure]
#myDynamicColumn varchar(50)
AS BEGIN
EXEC('SELECT ''value'' AS ' + #myDynamicColumn)
END
Both the upvoted answers are very dangerous here, both are wide open to injection attacks and should not be used.
When injecting dynamic object names you must ensure you properly quote your object names. SQL Server has a built in function for that, QUOTENAME. Thus what you should actually be doing is the following:
CREATE PROCEDURE [My_Procedure] #myDynamicColumn sysname
AS BEGIN
DECLARE #SQL nvarchar(MAX) = N'SELECT ''value'' AS ' + QUOTENAME(#myDynamicColumn) + N';';
EXEC sys.sp_executesql #SQL;
END
You'll note I also change the data type of the parameter to sysname, a synonym for nvarchar(128) NOT NULL, which is the data type SQL Server uses internally for object names.