Reversing COLUMN DATA by dynamically passing table name and Column Name - sql-server

I want to reverse a COLUMN DATA dynamically by passing table name and Column Name
DECLARE #TABLE_NAME NVARCHAR(300) -- to pass table name dynamically
DECLARE #COLUMN_NAME NVARCHAR(300) -- to pass column name dynamically
SET #TABLE_NAME = 'TEST1' -- Passing table name
SET #COLUMN_NAME = 'SSN' -- Passing column Name
DECLARE #OUTPUT NVARCHAR(MAX) -- to pass the selected column data to update
SET #OUTPUT = 'SELECT'+' '+#COLUMN_NAME+' '+'FROM'+#TABLE_NAME
DECLARE #UPDATE_EXEC NVARCHAR(MAX) -- To exec the Final update result
SET #UPDATE_EXEC = 'UPDATE ['+#TABLE_Name + ']'+'SET'+' '+#COLUMN_NAME+
'=REVERSE(EXEC (#output))'
EXEC(#UPDATE_EXEC)
But I'm getting these errors:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'EXEC'.
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "#output"

You are trying to put EXEC in your update query, its not allowed. EXEC is use to execute the query, it can't be part of any query.
To reverse any column in your table you can do so like below,
SET #UPDATE_EXEC = 'UPDATE ['+#TABLE_Name + ']'+'SET'+' '+#COLUMN_NAME+ '=REVERSE('+#COLUMN_NAME+')';
EXEC(#UPDATE_EXEC);

Related

Copy column from one table to another table with condition

ALTER PROCEDURE [dbo].[Timesheet_update]
AS
BEGIN
DECLARE #sql2 nvarchar(max), #status nvarchar(1)
SET #sql2 = 'insert into s21022020 (s21_stfno) select m_stfno from master where m_status<>'D''
EXECUTE (#sql2)
END
EXECUTE Timesheet_update
Results in an error:
Msg 207, Level 16, State 1, Line 23
Invalid column name 'D'.
m_status column contain data =D
I don't understand why you feel the need to make this a dynamic SQL - just write the statement directly inside the stored procedure - like this:
ALTER PROCEDURE [dbo].[Timesheet_update]
AS
BEGIN
INSERT INTO s21022020 (s21_stfno)
SELECT m_stfno
FROM master
WHERE m_status <> 'D'
END

SQL Server: get column value from string column name, assign value to variable

In SQL Server in a stored procedure, I want to get the value in a column of a single-row table given the column name, and assign that value to a variable. The column name may be different every time (I use T-SQL to interrogate the schema at run time).
The example given below is as minimal as I can make it, the important thing is that you cannot assume that the column name will always be entity_client, it could be anything at all, though (due to interrogation of INFORMATION SCHEMA) we will have the value assigned to the variable #entity_column_name.
Example preparation SQL:
IF OBJECT_ID('tempdb..#foo') IS NOT NULL
BEGIN;
DROP TABLE #foo;
END;
CREATE TABLE #foo
(
id INT,
entity_client NVARCHAR(255)
);
INSERT INTO #foo VALUES (1, 'clientcode|client_number');
DECLARE #entity_column_name NVARCHAR(255) = 'entity_client';
DECLARE #entity_column_value NVARCHAR(255);
I have tried the following:
SELECT TOP 1 #entity_column_name = [#entity_column_value]
FROM #foo;
...which generates an error
Invalid column name '#entity_column_value'
I have also tried:
EXEC('SELECT TOP 1 #entity_column_value = [' + #entity_column_name + '] FROM #foo;');
which generates another error
Must declare the scalar variable "#entity_column_value"
The following works, but unfortunately the column name is hard-coded - I wanted to be able to vary the column name:
SELECT TOP 1 #entity_column_value = [entity_client]
FROM #foo;
Yes, I have looked on SO and found the following questions, but they do not provide an answer where the value is assigned to a variable, in both cases the SELECT output is simply dumped to screen:
Get column value from string column name sql
Get column value from dynamically achieved column name
This will actually work but you need to declare the output variable:
DECLARE #entity_column_name NVARCHAR(255) = 'entity_client';
DECLARE #entity_column_value NVARCHAR(255);
DECLARE #tsql NVARCHAR(1000) = 'SELECT TOP 1 #entity_column_value = [' + #entity_column_name + '] FROM #foo;'
EXEC sp_executesql #tsql, N'#entity_column_value NVARCHAR(255) OUTPUT',
#entity_column_value OUTPUT;

Did not find exact example

I am getting this error:
Msg 102, Level 15, State 1, Line 9 Incorrect syntax near '+'.
When executing the following code:
DECLARE #Source nVARCHAR(30)
set #source = 'Srce.srce'
select #Source
--drop table #temp1
select 'xx' col1
INTO #temp
from #Source + .dbo.table1
You can not pass the name of database through variable.
If you want to forward the name of the database using the variable you have to use dynamic SQL.

Add a column, with a derived column name, to an existing table in SQL Server 2014

DECLARE
#countFlag INT,
#maxNum INT = 5,
#addingName NVARCHAR(6)
SET #countFlag = 1
WHILE (#countFlag <= #maxNum)
BEGIN
SET #addingName = 'name' + CAST(#countFlag AS NVARCHAR(2))
ALTER TABLE TableName
ADD
#addingName NVARCHAR(30)
SET #countFlag = #countFlag + 1
END
========================================================
This is called at the beginning of a set of procedures. #maxNum is actually passed in based on a question to the operator and changes the 'shape' of an existing db to include more columns. I would like to have the resulting column names be something like "name1" "name2" etc. but I am getting an "Incorrect syntax near '#addingName'" after the ADD statement when I execute it. What am I doing wrong here?
You cannot do it in that way, you should compose the query dynamically and execute it with Exec:
DECLARE #sqlCommand varchar(200)
SET #sqlCommand = 'ALTER TABLE TableName ADD ' + #addingName + ' NVARCHAR(30) '
EXEC (#sqlCommand)

How do I run a query from a function, when the table name is passed in as argument

I am writing a function that would take table-name as argument.
I know the column name I need out of the table, but the table name + table owner is dynamically passed in (well I need that to be the case, but it is currently not working).
It kind of looks like this:
CREATE FUNCTION [myowner].
[alex_diff](#fromdate datetime, #todate datetime, #table_name varchar(256), #country_code varchar(3))
RETURNS int
AS
BEGIN
...
set #date_string = (select calendar_month2 from ??? where calendar_year=#current_year and country_code = #country_code)
...
END
I couldn't put #table_name in place of '???'
That gave me error:
Msg 1087, Level 16, State 1, Procedure alex_business_date_diff, Line
53 Must declare the table variable "#table_name".
What can I do to execute SQL on the dynamically passed table name?
I have tried doing the following:
set #statement = 'select #output=' + #column_name + ' from ' + #table_name + ' where calendar_year=' + cast(#current_year as varchar(4)) + ' and country_code = ' + #country_code;
EXEC sp_executesql #statement, N'#output varchar(31) OUTPUT', #date_string OUTPUT
But get this error (when I try to run the function):
Msg 557, Level 16, State 2, Line 1 Only functions and some extended
stored procedures can be executed from within a function.
You could use CLR in SQL Server and take advantage of the .NET language which would run dynamic sql.
You can create a stored procedure with all your dynamic manipulations and consume the result via output parameter.

Resources