For the last couple days I am pulling my hair out because of a problem I have.
In a stored procedure, I want to use the column name as parameter to update a value in the table.
I have the following code
ALTER PROCEDURE [dbo].[Item_Update_Single]
#Id nvarchar(15),
#ColumnName nvarchar(80),
#NewValue nvarchar(80)
AS
DECLARE #sql NVARCHAR(MAX)
SET #sql = N'UPDATE [Item] SET [' + QUOTENAME(#ColumnName) + ']' + '= ' + QUOTENAME(#NewValue) +' WHERE [Id] = ' + #Id
PRINT #sql
The stored procedure is running fine, no errors, but the table is not updated. If I run the #SQL string in query window, the data is updated.
I am a sort of newbie but what did I do wrong here?
You never execute your dynamic statement. Your use of QUOTENAME is also wrong. '[' + QUOTENAME(#ColumnName) + ']' would result in [[ColumnName]] and QUOTENAME(#NewValue) would refer to a column with the name of what ever value is in #NewValue, not a string literal. You should be parametrising the statement and properly injecting the dynamic object:
ALTER PROCEDURE [dbo].[Item_Update_Single] #Id int, --Guess this is actually an int
#ColumnName sysname, --Corrected data type
#NewValue nvarchar(80) --I assume this is correct
AS
BEGIN
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'UPDATE dbo.[Item] SET ' + QUOTENAME(#ColumnName) + ' = #NewValue WHERE [Id] = #ID;'
EXEC sys.sp_executesql #SQL, N'#NewValue nvarchar(80),#Id int', #NewValue, #ID;
END
This, however, seems like an XY Problem. Solutions like this are almost always a bad idea and often infer a significant design flaw.
Related
When I want to add datetime column to entire table I can write a stored procedure which takes a date as input and then stores it into the table - like so:
ALTER PROCEDURE [dbo].[set_datettime]
(#importDate VARCHAR(100))
AS
BEGIN
UPDATE [dbo].[table1]
SET uploadDate = #importDate
END
But when I want to make the table dynamic I need to use sp_executesql. So my thought is I can do this:
ALTER PROCEDURE [dbo].[set_datettime]
(#tableName VARCHAR(100), #importDate VARCHAR(100))
AS
BEGIN
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = 'UPDATE dbo.' + quotename(#tableName) + ' SET uploadDate = #importDate';
EXECUTE sp_executesql #Sql
END
but now I get an error:
Error Message: Must declare the scalar variable #importDate
Despite clearly declaring the variable. Even if I try to explicitly declare the variable again I get the error that I cant declare duplicate variables.
Other thing which I tried was to do:
SET #Sql = 'UPDATE dbo.' + quotename(#tableName) + ' SET uploadDate = ' + #importDate;
But this throws an error
Invalid column name 10-10-2019
Lastly I was able to accomplish the task (somewhat) by changing to
SET #Sql = 'UPDATE dbo.' + quotename(#tableName) + ' SET uploadDate = GETDATE()';
But in this solution I define the date in the stored procedure and doesn't take it as input, which is not ideal.
How can I have dynamic table definition while still keeping the date input variable dynamic also?
You need to parametrise your dynamic statement. I'm typing on my phone right now, so I apologise for any typographical errors:
EXEC sp_executesql #SQL, N'#importdate date', #importdate;
Never inject parameters in your dynamic statements. It creates huge security flaws in your SQL, called SQL Injection.
Edit: not on my phone now, so can write out the complete SP:
ALTER PROCEDURE [dbo].[set_datettime]
(#tableName sysname, #importDate date)
AS
BEGIN
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = 'UPDATE dbo.' + quotename(#tableName) + ' SET uploadDate = #importDate;';
EXECUTE sp_executesql #Sql, N'#importDate date', #importDate;
END;
Test it first:
declare #tableName varchar(100) = 'sometable'
, #importDate varchar(100) = '10-10-2019'
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = 'UPDATE dbo.' + quotename(#tableName) + ' SET uploadDate = ' + #importDate
select #Sql
This give you an incorrect statement:
UPDATE dbo.[sometable] SET uploadDate = 10-10-2019
Try this:
SET #Sql = 'UPDATE dbo.' + quotename(#tableName) + ' SET uploadDate = ' + '''' + #importDate + ''''
Which gives you
UPDATE dbo.[sometable] SET uploadDate = '10-10-2019'
I have stored procedure where I have parameter with datatype sql_variant. This parameter is then converted and inserted into parameter that is nvarchar(MAX) datatype. Inserting dates and floats are working fine. Then as example inserting into varchar(60) cell doesn't seem to work and only inserts first letter. When I add SELECT statements for the parameters in stored procedure it shows after executing the information to be inserted correctly and it only fails the actual insertion to table.
How to insert whole nvarchar to varchar(60) or similar cell?
Here are important parts of the code without too much extra:
CREATE PROCEDURE proc_name
#param1 nvarchar(30),
#param2 nvarchar(30),
#param3 sql_variant
AS
BEGIN
SET NOCOUNT ON;
DECLARE #update_param nvarchar(MAX);
SET #update_param = CONVERT(nvarchar(MAX), #param3);
-- Lots of not important stuff here such as getting datatype from INFORMATION_SCHEMA
DECLARE #Sql nvarchar(MAX);
SET #Sql = N' DECLARE #variable ' + QUOTENAME(#datatype) + N' = #update_param '
+ N' UPDATE table_name'
+ N' SET ' + #param1 + N' = #variable '
+ N' WHERE something = ' + #param2
Exec sp_executesql #Sql, N'#update_param nvarchar(MAX)', #update_param
Adding SELECT #Sql to the procedure gives following result:
DECLARE #variable [varchar] = #update_param
UPDATE table_name
SET column_name = #variable
WHERE something = thingsome
When #param1 = column_name, #param2 = thingsome
Edit: I read multiple questions on this topic and they all told to declare nvarchar length. Here I have it declared as nvarchar(MAX).
Edit2: Added code bits.
Edit3: After adding code and help in comments the answer is that there is length undeclared for #datatype in #Sql
This doesn't answer the question at hand, however, the SP you have is open to injection. Raw string concatenation like that is a dangerous game to play. This is far safer:
CREATE PROCEDURE proc_name
#param1 nvarchar(30),
#param2 nvarchar(30),
#param3 sql_variant
AS
BEGIN
SET NOCOUNT ON;
DECLARE #update_param nvarchar(MAX);
SET #update_param = CONVERT(nvarchar(MAX), #param3);
-- Lots of not important stuff here such as getting datatype from INFORMATION_SCHEMA
DECLARE #Sql nvarchar(MAX);
SET #Sql = N' DECLARE #variable ' + QUOTENAME(#datatype) + N' = #dupdate_param' --Where is the value of #datatype coming from?
+ N' UPDATE table_name'
+ N' SET ' + QUOTENAME(#param1) + N' = #variable '
+ N' WHERE something = #dparam2;'
Exec sp_executesql #Sql, N'#dupdate_param nvarchar(MAX), #dparam2 nvarchar(30)',#dupdate_param = #update_param, #dparam = #param2;
GO
create procedure sp_First
#columnname varchar
AS
begin
select #columnname from Table_1
end
exec sp_First 'sname'
My requirement is to pass column names as input parameters.
I tried like that but it gave wrong output.
So Help me
You can do this in a couple of ways.
One, is to build up the query yourself and execute it.
SET #sql = 'SELECT ' + #columnName + ' FROM yourTable'
sp_executesql #sql
If you opt for that method, be very certain to santise your input. Even if you know your application will only give 'real' column names, what if some-one finds a crack in your security and is able to execute the SP directly? Then they can execute just about anything they like. With dynamic SQL, always, always, validate the parameters.
Alternatively, you can write a CASE statement...
SELECT
CASE #columnName
WHEN 'Col1' THEN Col1
WHEN 'Col2' THEN Col2
ELSE NULL
END as selectedColumn
FROM
yourTable
This is a bit more long winded, but a whole lot more secure.
No. That would just select the parameter value. You would need to use dynamic sql.
In your procedure you would have the following:
DECLARE #sql nvarchar(max) = 'SELECT ' + #columnname + ' FROM Table_1';
exec sp_executesql #sql, N''
Try using dynamic SQL:
create procedure sp_First #columnname varchar
AS
begin
declare #sql nvarchar(4000);
set #sql='select ['+#columnname+'] from Table_1';
exec sp_executesql #sql
end
go
exec sp_First 'sname'
go
This is not possible. Either use dynamic SQL (dangerous) or a gigantic case expression (slow).
Create PROCEDURE USP_S_NameAvilability
(#Value VARCHAR(50)=null,
#TableName VARCHAR(50)=null,
#ColumnName VARCHAR(50)=null)
AS
BEGIN
DECLARE #cmd AS NVARCHAR(max)
SET #Value = ''''+#Value+ ''''
SET #cmd = N'SELECT * FROM ' + #TableName + ' WHERE ' + #ColumnName + ' = ' + #Value
EXEC(#cmd)
END
As i have tried one the answer, it is getting executed successfully but while running its not giving correct output, the above works well
You can pass the column name but you cannot use it in a sql statemnt like
Select #Columnname From Table
One could build a dynamic sql string and execute it like EXEC (#SQL)
For more information see this answer on dynamic sql.
Dynamic SQL Pros and Cons
As mentioned by MatBailie
This is much more safe since it is not a dynamic query and ther are lesser chances of sql injection . I Added one situation where you even want the where clause to be dynamic . XX YY are Columns names
CREATE PROCEDURE [dbo].[DASH_getTP_under_TP]
(
#fromColumnName varchar(10) ,
#toColumnName varchar(10) ,
#ID varchar(10)
)
as
begin
-- this is the column required for where clause
declare #colname varchar(50)
set #colname=case #fromUserType
when 'XX' then 'XX'
when 'YY' then 'YY'
end
select SelectedColumnId from (
select
case #toColumnName
when 'XX' then tablename.XX
when 'YY' then tablename.YY
end as SelectedColumnId,
From tablename
where
(case #fromUserType
when 'XX' then XX
when 'YY' then YY
end)= ISNULL(#ID , #colname)
) as tbl1 group by SelectedColumnId
end
First Run;
CREATE PROCEDURE sp_First #columnname NVARCHAR(128)--128 = SQL Server Maximum Column Name Length
AS
BEGIN
DECLARE #query NVARCHAR(MAX)
SET #query = 'SELECT ' + #columnname + ' FROM Table_1'
EXEC(#query)
END
Second Run;
EXEC sp_First 'COLUMN_Name'
Please Try with this.
I hope it will work for you.
Create Procedure Test
(
#Table VARCHAR(500),
#Column VARCHAR(100),
#Value VARCHAR(300)
)
AS
BEGIN
DECLARE #sql nvarchar(1000)
SET #sql = 'SELECT * FROM ' + #Table + ' WHERE ' + #Column + ' = ' + #Value
--SELECT #sql
exec (#sql)
END
-----execution----
/** Exec Test Products,IsDeposit,1 **/
I have 6 table with different fields. I want to access table name dynamically. is there any idea to do it?
My code is below this is simple procedure which I want to make dynamic to use in c#. how to do it?
Create procedure [dbo].[Insert_Data] (#Id int,#FeesHead nchar(20),#Fees int,#Remarks nchar(20))
as
begin
Insert into FeesHead(ID,FeesHead,Fees,Remarks)values(#Id,#FeesHead,#Fees,#Remarks)
End
Don't go there.
It's a bad idea since you will end up with a long, inefficient stored procedure that will be vulnerable to SQL injection attacks and have performance issues.
Writing an insert stored procedure for each table is the way to go.
You wrote you have six different tables with different columns, so writing a stored procedure to handle inserts for all of them will require you to send all the parameters for all columns as well as a parameter for the table name, and a nested if...else with 6 possible paths, one for each table.
This will end up as a long, messy, poorly written code at best, bad in each parameter: security, performance, code readability and maintainability.
The only way that makes some sense to achieve such a goal is to write individual insert stored procedures for each table, and then write a stored procedure that will take all of the possible parameters and the table name and inside of it decide what insert stored procedure to execute based on the value of the table name parameter. However, you will be better off leaving conditions like these to the SQL client (your c# code in this case) then to SQL Server.
Its very easy to do.........
Just call the sql query using Data Adapter.
select TABLE_NAME from INFORMATION_SCHEMA.TABLES
As you said you need dynamic SQL like this:
Create procedure [dbo].[Insert_Data]
(
#TableName nvarchar(512),
#Values nvarchar(max)
)
BEGIN
DECLARE #SQL nvarchar(max)
SELECT #SQL = 'INSERT INTO ' + #TableName + ' VALUES (' + #Values + ')'
EXEC(#SQL)
END
Note that #Values will be like this '1, ''name'', 10.2' and with the same order of columns.
or
Create procedure [dbo].[Insert_Data]
(
#TableName nvarchar(512),
#Fields nvarchar(max),
#Values nvarchar(max)
)
BEGIN
DECLARE #SQL nvarchar(max)
SELECT #SQL = 'INSERT INTO ' + #TableName + ' (' + #Fields + ') VALUES (' + #Values + ')'
EXEC(#SQL)
END
To more ability to handle column order and remove identity columns.
As Robert Harvey mentioned it is a bad idea, anyway if you want to you can do something like....
CREATE PROCEDURE Insert_Data
#TableName SYSNAME
,#Column1 SYSNAME = NULL
,#Column2 SYSNAME = NULL
,#Column3 SYSNAME = NULL
,#Value1 NVARCHAR(100) = NULL
,#Value2 NVARCHAR(100) = NULL
,#Value3 NVARCHAR(100) = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = N' INSERT INTO ' + QUOTENAME(#TableName)
+ N' ( '
+ STUFF(
CASE WHEN #Column1 IS NOT NULL
THEN N',' + QUOTENAME(#Column1) ELSE N'' END
+ CASE WHEN #Column2 IS NOT NULL
THEN N',' + QUOTENAME(#Column2) ELSE N'' END
+ CASE WHEN #Column3 IS NOT NULL
THEN N',' + QUOTENAME(#Column3) ELSE N'' END
,1,1,'')
+ N' ) '
+ N' VALUES ( '
+ STUFF(
CASE WHEN #Value1 IS NOT NULL
THEN N', #Value1' ELSE N'' END
+ CASE WHEN #Value2 IS NOT NULL
THEN N', #Value2' ELSE N'' END
+ CASE WHEN #Value3 IS NOT NULL
THEN N', #Value3' ELSE N'' END
,1,1,'')
+ N' ) '
Exec sp_executesql #Sql
,N'#Value1 NVARCHAR(100),#Value2 NVARCHAR(100),#Value3 NVARCHAR(100)'
,#Value1
,#Value2
,#Value3
END
I am using SQL Server 2012, I am going to Create Store Procedure which copies a column from a table in a variable, Could any one please tell me what is Wrong with this code?
alter Procedure Id_Fetch
#Col varchar(50)=null,
#Table VARCHAR(50)=Null,
#OrdrBy Varchar(40)=null
as
Begin
declare #TempCol nvarchar (100)
Exec(' SELECT '+#TempCol+' = '+#Col+' from ' + #Table +' order by '+#OrdrBy )
its showing error "Incorrect Syntax near '='
A little modification ...... Use TOP 1 in your select as if more than one value is returned by your select it will throw an error.
Use SYSNAME datatype for your Column names and table names.
Use QUOTENAME() function around your object name parameters, which puts square brackets [] around the passed parameter value and forces it to be treated as an object name (Protection against Sql Injection attack).
Use sp_executesql instead of EXEC and concatenating parameter values into string and executing again protects you against Sql Injection attack.
ALTER PROCEDURE Id_Fetch
#Col SYSNAME,
#Table SYSNAME,
#OrdrBy SYSNAME,
#Col_Value NVARCHAR(100) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = N' SELECT TOP 1 #Col_Value = ' + QUOTENAME(#Col)
+ N' FROM ' + QUOTENAME(#Table)
+ N' ORDER BY ' + QUOTENAME(#OrdrBy)
EXECUTE sp_executesql #Sql
,N'#Col_Value NVARCHAR(100) OUTPUT'
,#Col_Value OUTPUT
END