I have a simple Cursor in SQL Server that I would like to adapt to use in Teradata.
The goal of the cursor is to collect the names of a series of tables and rename them using cursor logic.
I already change most of the cursor code to use in Teradata, but I'm still having some trouble to finish this.
So far I have:
DECLARE varTableOldName VARCHAR(500);
DECLARE varTableNewName VARCHAR(500);
DECLARE vardbName VARCHAR(100);
DECLARE varIDCod VARCHAR(5);
DECLARE varRename VARCHAR(100);
DECLARE varCt INT DEFAULT 0;
DECLARE renameTables CURSOR FOR
SELECT
DBname
,TBname
FROM (
SELECT
DatabaseName AS DBname
,TableName AS TBname
,LastAccessTimeStamp AS LADate
,(CURRENT_DATE - CAST(LastAccessTimeStamp AS DATE)) AS NAccessDate
FROM
DBC.TablesV
WHERE
1=1
AND TableKind = 'T'
AND DatabaseName IN ('PD_BACKUP')
GROUP BY
DatabaseName
,TableName
,LastAccessTimeStamp
,LastAlterTimeStamp
) tbHig
WHERE NAccessDate IS NULL OR NAccessDate >= 180
ORDER BY DBname, TBname
FOR READ ONLY;
OPEN renameTables;
FETCH NEXT FROM renameTables
INTO vardbName, varTableOldName;
WHILE (SQLCODE = 0)
DO
SET varTableNewName = vardbName || '_V' || CAST(EXTRACT(YEAR FROM CURRENT_TIMESTAMP) AS VARCHAR(20)) || '_' || CAST(varCt AS VARCHAR(20));
SET varTableOldName = vardbName || '.' || varTableOldName;
SET varRename = 'RENAME TABLE ' || varTableOldName || ' TO ' || varTableNewName;
EXECUTE IMMEDIATE varRename;
SET varCt = varCt + 1;
FETCH NEXT FROM renameTables INTO vardbName, varTableOldName;
END WHILE;
CLOSE renameTables;
I think the problem is with some syntax details or something.
Can anyone guide me with this please?
Related
I am trying to write a stored procedure in SQL Server which will:
Take a list of integers as input ( let's assume these integers are "profile_id")
pick up all the table names which has a column named as "profile_id" into a cursor
loop through the cursor and print the profile_id value when it matches one of them in the input list of params.
Now the problem is: I am executing the procedure like this:
EXEC dbo.de_dup '1234,2345';
and getting a syntax error when trying to execute the commented out line below (Please see the procedure):
set #id = (select profile_id from #tname where profile_id in #a_profile_id );
Questions:
What would be the right way of executing and setting the value inside a cursor?
What is way (in our case) to pass a list of integers to this procedure?
This is my procedure:
ALTER PROCEDURE dbo.de_dup
(#a_profile_id nvarchar(MAX))
AS
DECLARE #tname VARCHAR(max),
#id int;
DECLARE tables_cursor CURSOR FOR
SELECT
a.TABLE_CATALOG +'.'+a.TABLE_SCHEMA + '.'+ a.TABLE_NAME AS table_name
FROM
JobApp.INFORMATION_SCHEMA.COLUMNS a
LEFT OUTER JOIN
JobApp.INFORMATION_SCHEMA.VIEWS b ON a.TABLE_CATALOG = b.TABLE_CATALOG
AND a.TABLE_SCHEMA = b.TABLE_SCHEMA
AND a.TABLE_NAME = b.TABLE_NAME
WHERE
a.COLUMN_NAME = 'profile_id'
GROUP BY
a.TABLE_CATALOG, a.TABLE_SCHEMA, a.TABLE_NAME, a.COLUMN_NAME;
OPEN tables_cursor;
FETCH NEXT FROM tables_cursor INTO #tname;
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT #a_profile_id ;
PRINT #tname ;
--set #id= (select profile_id from #tname where profile_id in #a_profile_id );
--PRINT 'id : ' + #id;
FETCH NEXT FROM tables_cursor INTO #tname;
END;
CLOSE tables_cursor;
DEALLOCATE tables_cursor;
GO;
Please let me know should I provide more clarification. Thanks in advance.
This solution is using the dynamic SQL, As per my knowledge we need to use the dynamic SQL if we have the table name in a variable.
DBFIDDLE working code
Query:
CREATE PROCEDURE dbo.de_dup (#a_profile_id NVARCHAR(MAX))
AS
BEGIN
DECLARE #tname VARCHAR(max)
,#id INT
,#dynamicSQL NVARCHAR(MAX);
DECLARE #matched_tables TABLE (Name NVARCHAR(255));
DECLARE #matched_profileIds TABLE (profile_id INT);
DECLARE #profile_ids NVARCHAR(MAX) = #a_profile_id
INSERT INTO #matched_tables
SELECT DISTINCT a.TABLE_SCHEMA + '.' + a.TABLE_NAME AS table_name
FROM INFORMATION_SCHEMA.COLUMNS a
WHERE a.COLUMN_NAME = 'profile_id'
WHILE EXISTS (
SELECT 1
FROM #matched_tables
)
BEGIN
SELECT TOP 1 #tname = [Name]
FROM #matched_tables
SET #dynamicSQL = CONCAT (
'select profile_id from '
,#tname
,' WHERE '
,''','
,#profile_ids
,','''
,' LIKE '
,'''%,'
,''''
,' + CAST(profile_id AS NVARCHAR(MAX)) + '
,''',%'
,''''
)
PRINT #dynamicSQL;
INSERT INTO #matched_profileIds
EXEC (#dynamicSQL)
DELETE
FROM #matched_tables
WHERE [Name] = #tname
END
SELECT *
FROM #matched_profileIds
END
Dynamic SQL that gets formed is
SELECT profile_id
FROM dbo.TestTable
WHERE ',123,456,789,1011,1213,' LIKE '%,' + CAST(profile_id AS NVARCHAR(MAX)) + ',%'
So I have solved a similar issue with a table-valued function called Split. It splits a delimited list into rows in a table, which you can then JOIN or use as a subquery in your code.
CREATE FUNCTION [dbo].[Split]
(
#char_array varchar(500), #delimiter char(1)
)
RETURNS
#parsed_array table
(
Parsed varchar(50)
)
AS
BEGIN
DECLARE #parsed varchar(50), #pos int
SET #char_array = LTRIM(RTRIM(#char_array))+ #delimiter
SET #pos = CHARINDEX(#delimiter, #char_array, 1)
IF REPLACE(#char_array, #delimiter, '') <> ''
BEGIN
WHILE #pos > 0
BEGIN
SET #parsed = LTRIM(RTRIM(LEFT(#char_array, #pos - 1)))
IF #parsed <> ''
BEGIN
INSERT INTO #parsed_array (Parsed)
VALUES (#parsed)
END
SET #char_array = RIGHT(#char_array, LEN(#char_array) - #pos)
SET #pos = CHARINDEX(#delimiter, #char_array, 1)
END
END
RETURN
END
GO
You would use it like so
SELECT f.Parsed INTO #s FROM dbo.Split(#a_profile_id, ',') f;
Then in your query (only the relevant part for brevity)
select profile_id from #tname where profile_id in(select Parsed from #s);
I left out the set #id= because that will produce unpredictable results for the value of #id if the select statement returns multiple results. But you indicated this is not the actual code anyway so...
Disclaimer: I got the meat of the Split function from someone else online. If I could remember who I would attribute it properly.
I need a to create an sql script which from a table table will build a dynamic sql request in the following way:
select ID || ',' || NAME || ',' || CODE
from TABLE_TEST;
The table name is received as an input parameter.
My SQL script is as follows;
spool exportTable.log
SET HEAD OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET LINESIZE 32000
SET PAGESIZE 0
SET TERMOUT OFF
SET ECHO OFF
SET COLSEP ,
procedure CreerReq(sTable in Varchar) is
dbms_output.put_line('dans CreerReq');
sqlreq VARCHAR2(2000);
sChaine VARCHAR2(4000):='select';
TYPE t_tab IS TABLE OF VARCHAR2(4000);
l_tab t_tab;
l_tab_Id t_tab;
l_ref_cursor SYS_REFCURSOR;
dbms_output.put_line(sChaine);
begin
sqlreq := 'select column_name from all_tab_cols WHERE table_name' || sTable;
dbms_output.put_line(sqlreq);
OPEN l_ref_cursor FOR sqlreq;
LOOP
FETCH l_ref_cursor BULK COLLECT INTO l_tab_Id,l_tab limit 1000;
EXIT WHEN l_tab.COUNT=0;
FOR i IN l_tab.first .. l_tab.last LOOP
sChaine:=l_tab(i) ' || ','';
END LOOP;
CLOSE l_ref_cursor;
dbms_output.put_line(sChaine);
End CreerReq;
BEGIN
dbms_output.put_line('&1');
CreerReq(&1);
END;
/
spool off;
However this is returning me the following error:
ORA-00900: invalid SQL statement
Any help please?
CREATE or replace FUNCTION build_select (
p_owner IN VARCHAR2
, p_table_name IN VARCHAR2
)
RETURN VARCHAR2
AS
l_ret VARCHAR2 (32767);
BEGIN
FOR eachcol IN ( SELECT column_name
, LEAD (column_name)
OVER (
PARTITION BY table_name ORDER BY column_id
)
next_column
FROM all_tab_cols
WHERE owner = p_owner
AND table_name = p_table_name
ORDER BY column_id)
LOOP
l_ret := l_ret || eachcol.column_name || CASE WHEN eachcol.next_column IS NULL THEN NULL ELSE ',' END;
END LOOP;
IF l_ret IS NULL
THEN
raise_application_error (-20001, 'table ' || p_owner || '.' || p_table_name || ' not found');
END IF;
l_ret := 'select ' || l_ret || ' from ' || p_owner || '.' || p_table_name;
RETURN l_ret;
END build_select;
So let's test it out:
begin dbms_output.put_line(build_select('SYS', 'ALL_TAB_COLS')); end;
Results in:
select OWNER,TABLE_NAME,COLUMN_NAME,DATA_TYPE,DATA_TYPE_MOD,DATA_TYPE_OWNER,DATA_LENGTH,DATA_PRECISION,DATA_SCALE,NULLABLE,COLUMN_ID,DEFAULT_LENGTH,DATA_DEFAULT,NUM_DISTINCT,LOW_VALUE,HIGH_VALUE,DENSITY,NUM_NULLS,NUM_BUCKETS,LAST_ANALYZED,SAMPLE_SIZE,CHARACTER_SET_NAME,CHAR_COL_DECL_LENGTH,GLOBAL_STATS,USER_STATS,AVG_COL_LEN,CHAR_LENGTH,CHAR_USED,V80_FMT_IMAGE,DATA_UPGRADED,HIDDEN_COLUMN,VIRTUAL_COLUMN,SEGMENT_COLUMN_ID,INTERNAL_COLUMN_ID,HISTOGRAM,QUALIFIED_COL_NAME from SYS.ALL_TAB_COLS
Here is a simpler build_select function:
CREATE OR REPLACE FUNCTION build_select (
p_owner IN VARCHAR2
, p_table_name IN VARCHAR2
)
RETURN VARCHAR2
AS
l_ret VARCHAR2 (32767);
BEGIN
SELECT
LISTAGG (column_name, ',') WITHIN GROUP (ORDER BY column_id)
INTO l_ret
FROM all_tab_cols
WHERE table_name = p_table_name
AND owner = p_owner;
IF l_ret IS NULL
THEN
raise_application_error (-20001, 'table ' || p_owner || '.' || p_table_name || ' not found');
END IF;
l_ret := 'select ' || l_ret || ' from ' || p_owner || '.' || p_table_name;
RETURN l_ret;
END build_select;
I haven't worked with oracle in a while. But on sql server this is how it can be done. Look through this code and it might point you to the right direction:
/* This stored procedure builds dynamic SQL and executes
using sp_executesql */
Create Procedure sp_EmployeeSelect
/* Input Parameters */
#EmployeeName NVarchar(100),
#Department NVarchar(50),
#Designation NVarchar(50),
#StartDate DateTime,
#EndDate DateTime,
#Salary Decimal(10,2)
AS
Set NoCount ON
/* Variable Declaration */
Declare #SQLQuery AS NVarchar(4000)
Declare #ParamDefinition AS NVarchar(2000)
/* Build the Transact-SQL String with the input parameters */
Set #SQLQuery = 'Select * From tblEmployees where (1=1) '
/* check for the condition and build the WHERE clause accordingly */
If #EmployeeName Is Not Null
Set #SQLQuery = #SQLQuery + ' And (EmployeeName = #EmployeeName)'
If #Department Is Not Null
Set #SQLQuery = #SQLQuery + ' And (Department = #Department)'
If #Designation Is Not Null
Set #SQLQuery = #SQLQuery + ' And (Designation = #Designation)'
If #Salary Is Not Null
Set #SQLQuery = #SQLQuery + ' And (Salary >= #Salary)'
If (#StartDate Is Not Null) AND (#EndDate Is Not Null)
Set #SQLQuery = #SQLQuery + ' And (JoiningDate
BETWEEN #StartDate AND #EndDate)'
/* Specify Parameter Format for all input parameters included
in the stmt */
Set #ParamDefinition = ' #EmployeeName NVarchar(100),
#Department NVarchar(50),
#Designation NVarchar(50),
#StartDate DateTime,
#EndDate DateTime,
#Salary Decimal(10,2)'
/* Execute the Transact-SQL String with all parameter value's
Using sp_executesql Command */
Execute sp_Executesql #SQLQuery,
#ParamDefinition,
#EmployeeName,
#Department,
#Designation,
#StartDate,
#EndDate,
#Salary
If ##ERROR <> 0 GoTo ErrorHandler
Set NoCount OFF
Return(0)
ErrorHandler:
Return(##ERROR)
GO
I have a query, that returns multiple tables, something like that:
SELECT TableName, DatabaseName +'.'+ TableName, ColumnName
FROM DBC.Columns
WHERE ColumnName = 'id'
And I need to loop through these tables by looking to the information stored in these tables, in order to get only specific tables.
I tried something like code below, using 'LOOP' and cursor, but it says that Query is invalid (code have been taken from here):
DECLARE cursor_Tables CURSOR FOR
SELECT DatabaseName || '.' || TableName
FROM DBC.Columns
WHERE ColumnName ='id';
OPEN cursor_Tables;
label1:
LOOP
FETCH cursor_Tables into tbName;
IF (SQLSTATE ='02000') THEN
LEAVE label1;
END IF;
CASE WHEN (
SELECT COUNT(*)
FROM prd3_db_tmd.K_PTY_NK01
WHERE id = 0 ) > 0
THEN tbName
END
END LOOP label1;
CLOSE cursor_Tables;
END;
How can I actually deal with this problem? Do I need to use procedure in addition? DBMS is Teradata
You need a Stored Procedure because this is the only place where you can use a cursor in Teradata.
REPLACE PROCEDURE testproc()
DYNAMIC RESULT SETS 1
BEGIN
DECLARE tbName VARCHAR(257);
DECLARE SqlStr VARCHAR(500);
-- temporary table to store the result set
CREATE VOLATILE TABLE _vt_(tbName VARCHAR(257)) ON COMMIT PRESERVE ROWS;
-- your existing query to return the table name
-- Better use ColumnsV instead of Columns
FOR cursor_Tables AS
SELECT DatabaseName || '.' || TABLENAME AS tbName
FROM DBC.ColumnsV
WHERE ColumnName ='id'
DO -- prepare the dynamic SQL ...
SET SqlStr =
'insert into _vt_
select ''' || cursor_tables.tbName || '''
from ' || cursor_tables.tbName || '
where id = 0
having count(*) > 0;
';
-- ... and run it
EXECUTE IMMEDIATE SqlStr;
END FOR;
BEGIN -- return the result set
DECLARE resultset CURSOR WITH RETURN ONLY FOR S1;
SET SqlStr = 'SELECT * FROM _vt_;';
PREPARE S1 FROM SqlStr;
OPEN resultset;
END;
DROP TABLE vt;
END;
If this is SQL Server you can check following SQL cursor, I edited the cursor declaration and the code within
Although they may differ from your requirement, I think you can modify easily
declare #sql nvarchar(max)
declare #tablename nvarchar(100)
DECLARE cursor_Tables CURSOR FOR
SELECT s.name + '.' + o.name
--s.name [schema], o.name [table]
FROM sys.Columns c
inner join sys.objects o on c.object_id = o.object_id
inner join sys.schemas s on s.schema_id = o.schema_id
WHERE c.Name ='id' and o.type = 'U'
/*
SELECT TableName, DatabaseName +'.'+ TableName, ColumnName
FROM DBC.Columns
WHERE ColumnName = 'id'
*/
OPEN cursor_Tables;
FETCH NEXT FROM cursor_Tables INTO #tablename
WHILE ##FETCH_STATUS = 0
BEGIN
-- print #tablename
set #sql = 'select case when count(*) > 0 then ''' + #tablename + ''' else '''' end from ' + #tablename
exec sp_executesql #sql
FETCH NEXT FROM cursor_Tables INTO #tablename
END
CLOSE cursor_Tables;
DEALLOCATE cursor_Tables;
On SQL Server, sp_MsForEachTable undocumented stored procedure can be used instead of a loop structure like a cursor
Please check the below SQL command
EXEC sp_MSForEachTable 'IF EXISTS(select * from sys.columns where name = ''Id'' and object_id = object_id(''?''))SELECT ''?'', COUNT(*) FROM ?'
The syntax may be difficult if you are using the sp_msforeachtable or sp_msforeachdb, but you can find samples on the web
You could create a variable to hold the number of rows and set it equal to the count:
DECLARE #count INT
SELECT #count = COUNT(*)
FROM prd3_db_tmd.K_PTY_NK01
WHERE id = 0
Then use an if statement to select the table if it has rows that meet your criteria:
IF #count > 0
BEGIN
SELECT tbName
END
Also as a side note without having SELECT in front of your CASE statement the syntax is invalid, you may want to try it with just adding SELECT in front of CASE if you don't like the way mentioned above
You need to use dynamic SQL. If you need to see the info on the table, you can create a synonym.
CURSOR cursor_Tables is
SELECT DatabaseName || '.' || TableName AS tbName
FROM DBC.Columns
WHERE ColumnName ='id';
begin
FOR R IN cursor_Tables
LOOP
execute immediate 'CREATE OR REPLACE SYNONYM your_synonym FOR '|| R.tbName ;
select *
from your_synonym;
END LOOP;
END;
Or if you want you can create a view.
SELECT col1,
col2,
col3,
EXEC GetAIntFromStoredProc(T.col1) AS col4
FROM Tbl AS T
WHERE (col2 = #parm)
How to write this SQL query in SQL Server 2008?
Thanks #twoleggedhorse.
Here is the solution.
First we created a function
CREATE FUNCTION GetAIntFromStoredProc(#parm Nvarchar(50)) RETURNS INTEGER
AS
BEGIN
DECLARE #id INTEGER
set #id= (select TOP(1) id From tbl where col=#parm)
RETURN #id
END
then we do the select query
Select col1, col2, col3,
GetAIntFromStoredProc(T.col1) As col4
From Tbl as T
Where col2=#parm
Functions are easy to call inside a select loop, but they don't let you run inserts, updates, deletes, etc. They are only useful for query operations. You need a stored procedure to manipulate the data.
So, the real answer to this question is that you must iterate through the results of a select statement via a "cursor" and call the procedure from within that loop. Here's an example:
DECLARE #myId int;
DECLARE #myName nvarchar(60);
DECLARE myCursor CURSOR FORWARD_ONLY FOR
SELECT Id, Name FROM SomeTable;
OPEN myCursor;
FETCH NEXT FROM myCursor INTO #myId, #myName;
WHILE ##FETCH_STATUS = 0 BEGIN
EXECUTE dbo.myCustomProcedure #myId, #myName;
FETCH NEXT FROM myCursor INTO #myId, #myName;
END;
CLOSE myCursor;
DEALLOCATE myCursor;
Note that ##FETCH_STATUS is a standard variable which gets updated for you. The rest of the object names here are custom.
You can create a temp table matching your proc output and insert into it.
CREATE TABLE #Temp (
Col1 INT
)
INSERT INTO #Temp
EXEC MyProc
As long as you're not doing any INSERT or UPDATE statements in your stored procedure, you will probably want to make it a function.
Stored procedures are for executing by an outside program, or on a timed interval.
The answers here will explain it better than I can:
Function vs. Stored Procedure in SQL Server
"Not Possible".
You can use a function instead of the stored procedure.
"Not Possible". You can do this using this query.
Initialize here
declare #sql nvarchar(4000)=''
Set Value & exec command of your sp with parameters
SET #sql += ' Exec spName #param'
EXECUTE sp_executesql #sql, N'#param type', #param = #param
Don't forget, if you just want to use the SP as a one-off query real quick to check something, all you have to do is pull the innards of the SP out and paste it in a new query window and do whatever you like at that point because it is no longer a SP.
Create a dynamic view and get result from it.......
CREATE PROCEDURE dbo.usp_userwise_columns_value
(
#userid BIGINT
)
AS
BEGIN
DECLARE #maincmd NVARCHAR(max);
DECLARE #columnlist NVARCHAR(max);
DECLARE #columnname VARCHAR(150);
DECLARE #nickname VARCHAR(50);
SET #maincmd = '';
SET #columnname = '';
SET #columnlist = '';
SET #nickname = '';
DECLARE CUR_COLUMNLIST CURSOR FAST_FORWARD
FOR
SELECT columnname , nickname
FROM dbo.v_userwise_columns
WHERE userid = #userid
OPEN CUR_COLUMNLIST
IF ##ERROR <> 0
BEGIN
ROLLBACK
RETURN
END
FETCH NEXT FROM CUR_COLUMNLIST
INTO #columnname, #nickname
WHILE ##FETCH_STATUS = 0
BEGIN
SET #columnlist = #columnlist + #columnname + ','
FETCH NEXT FROM CUR_COLUMNLIST
INTO #columnname, #nickname
END
CLOSE CUR_COLUMNLIST
DEALLOCATE CUR_COLUMNLIST
IF NOT EXISTS (SELECT * FROM sys.views WHERE name = 'v_userwise_columns_value')
BEGIN
SET #maincmd = 'CREATE VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), #userid) + ') as userid , '
+ CHAR(39) + #nickname + CHAR(39) + ' as nickname, '
+ #columnlist + ' compcode FROM dbo.SJOTran '
END
ELSE
BEGIN
SET #maincmd = 'ALTER VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), #userid) + ') as userid , '
+ CHAR(39) + #nickname + CHAR(39) + ' as nickname, '
+ #columnlist + ' compcode FROM dbo.SJOTran '
END
EXECUTE sp_executesql #maincmd
END
-----------------------------------------------
SELECT * FROM dbo.v_userwise_columns_value
For an instance I a select statement and it is returning 1000 rows. I need to execute a particular stored procedure for every row the the select statement is returning.
have you got any idea how can I do that?
Construct the EXECUTE statements in your select like this:
SELECT 'EXEC sp_whatever ' + parameter stuff
FROM your_table
Then run the results! Alternatively, paste your results into a spreadsheet package, and use string concatenation to construct the EXEC statements - just create a formula and paste it down the 1,000 rows. I personally prefer the first approach.
To clarify the "parameter stuff", take the example of a stored procedure that takes two int parameters that you want to take from columns you your_table. You'd then have something like this:
SELECT 'EXEC sp_whatever ' + CAST(field1 AS varchar) + ', ' + CAST(field2 AS varchar)
FROM your_table
Not the need to be careful with string fields here - you run the risk of inadvertently exposing yourself to your own SQL injection attack, as with any SQL string concatenation.
I am reading your "for an instance" as "this is a one-off task". If this is a task that needs automating, then one of the other answers may be the right approach.
You can do it like this:
declare #execstatementsbatch nvarchar(max)
select #execstatementsbatch = ''
SELECT #execstatementsbatch = #execstatementsbatch + 'EXEC UpdateQty ' + ItemCode + ', ' + QtyBO + '; '
FROM ITEMSPO
INNER JOIN .....
<some conditions>
exec(#execstatementsbatch)
Disclaimer: I'm not sure if I understand your question correctly.
Assuming you are on SQL Server 2005 upwards, you could create a table-valued user defined function and use the OUTER APPLY operator in your query.
Most RDBMS will let you select rows from stored procedure result sets. Just put your stored procedures in the FROM clause, as you would for common table expressions. For instance:
SELECT sp.ColumnInResultSet, t.BaseTableColumnName
FROM sp_whatever ( Args) sp INNER JOIN BaseTable t ON t.ID = sp.ID;
CREATE PROCEDURE dbo.usp_userwise_columns_value
(
#userid BIGINT
)
AS
BEGIN
DECLARE #maincmd NVARCHAR(max);
DECLARE #columnlist NVARCHAR(max);
DECLARE #columnname VARCHAR(150);
DECLARE #nickname VARCHAR(50);
SET #maincmd = '';
SET #columnname = '';
SET #columnlist = '';
SET #nickname = '';
DECLARE CUR_COLUMNLIST CURSOR FAST_FORWARD
FOR
SELECT columnname , nickname
FROM dbo.v_userwise_columns
WHERE userid = #userid
OPEN CUR_COLUMNLIST
IF ##ERROR <> 0
BEGIN
ROLLBACK
RETURN
END
FETCH NEXT FROM CUR_COLUMNLIST
INTO #columnname, #nickname
WHILE ##FETCH_STATUS = 0
BEGIN
SET #columnlist = #columnlist + #columnname + ','
FETCH NEXT FROM CUR_COLUMNLIST
INTO #columnname, #nickname
END
CLOSE CUR_COLUMNLIST
DEALLOCATE CUR_COLUMNLIST
IF NOT EXISTS (SELECT * FROM sys.views WHERE name = 'v_userwise_columns_value')
BEGIN
SET #maincmd = 'CREATE VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), #userid) + ') as userid , '
+ CHAR(39) + #nickname + CHAR(39) + ' as nickname, '
+ #columnlist + ' compcode FROM dbo.SJOTran '
END
ELSE
BEGIN
SET #maincmd = 'ALTER VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), #userid) + ') as userid , '
+ CHAR(39) + #nickname + CHAR(39) + ' as nickname, '
+ #columnlist + ' compcode FROM dbo.SJOTran '
END
--PRINT #maincmd
EXECUTE sp_executesql #maincmd
END
-----------------------------------------------
SELECT * FROM dbo.v_userwise_columns_value