How to add the column and than update the column in sql server using procedure - sql

i have created the table called test_exam
create table test_exam(id int,age int)
than i want through procedure add column called name and update it value.
i have made the procedure
create procedure [dbo].[abcd1] #tablename sysname
as
begin
declare #query nvarchar(4000)
declare #name_test varchar(20)
set #query = N'select top 10 * from transorg_DW.dbo.'+#tablename
print #query
alter table test_exam add name varchar(20);
update test_exam set name='shyam' where id=1;
exec sp_executesql
end
its through an error
invalid column name.
how to rectify this error?

You should call it dynamically and in separate, I think, it will for the column at the compile time so it is displaying error. For now you can do the following
DECLARE #sql NVARCHAR(500)
SET #sql = ' alter table purchase add stat int'
EXEC sp_executesql #sql
SET #sql = ' update purchase set stat=0'
EXEC sp_executesql #sql
Note: Please check the column existence if you would need to call multiple times

When you add any column to existing table then allow null or provide some default value.
And also prevent the DDL command from being executed more then once, otherwise it will throw error on next execution.
And for update its throw error because name column didn't exist while creating the proc. Update statement must as dynamic query.
create procedure [dbo].[abcd1] #tablename sysname
as
begin
declare #query nvarchar(4000)
declare #name_test varchar(20)
set #query = N'select top 10 * from transorg_DW.dbo.'+#tablename
print #query
if not exists(select * from sys.columns c join sys.tables t on c.object_id=t.object_id
where t.name='test_exam' and c.name='name')
begin
--new column added must be as null value or default value
alter table test_exam
add name varchar(20) null;
end
declare #query1 nvarchar(4000)
set #query1='update test_exam set name=''shyam'' where id=1';
exec (#query1)
exec sp_executesql
end
Enjoy hope this will help.

Related

Cannot get output variable from stored procedure when procedure written in dynamic sql

I am writing a procedure to produce an int output variable, but I'm not sure how to do this using dynamic sql. If I execute the below procedure I get the #AnlyNum value displayed in the results screen, but I just want #AnlyNum variable set with a value so I can use it. Thank you.
Create procedure [dbo].[sp_test] #Db varchar(50), #RwNum int, #AnlyNum int output
As
Begin
Declare #Sql nvarchar(max) =
'Select ''#AnlyNum'' = (Select AnlyId From '+#Db+'..Test order by AnlyId desc OFFSET '+convert(varchar(10),#RwNum)+' rows fetch next 1 rows only)'
End
exec(#Sql)
This removes SQL injection concerns by properly escaping the database name and also dynamically executing against that database instead of embedding the database name in the command. Also, you don't need #RwNum to be dynamic.
CREATE PROCEDURE dbo.test
#Db sysname,
#RwNum int,
#AnlyNum int output
AS
BEGIN
SET NOCOUNT ON;
DECLARE #exec nvarchar(max) = QUOTENAME(#Db) + N'.sys.sp_executesql',
#sql nvarchar(max) = N'SELECT #AnlyNum = AnlyId
From dbo.Test order by AnlyId desc
OFFSET #RwNum rows fetch next 1 rows only);';
EXEC #exec #sql, N'#AnlyNum int output, #RwNum int',
#AnlyNum output, #RwNum;
END

Table name variable in MS SQL query

I have dynamically created tables, like XXX_JOURNAL.
Where XXX - is table prefix (variable), and _JOURNAL - is constant in table name.
I need create UPDATE trigger on database, not on particular table, and use table name (prefix) as variable:
CREATE TRIGGER triggerName ON %_JOURNAL
FOR UPDATE
AS
UPDATE XXX_JOURNAL
SET COMPANY_ID = LEFT(tableName,3) //tableName = current table (XXX_JOURNAL)
WHERE ID = ID FROM inserted
So here I have two difficulties:
How to create one trigger for all tables LIKE %_JOURNAL?
How to use table name as the keyword for current table?
I know there are a lot of mistakes in syntax. For example, I cannot use '%_JOURNAL' as table name on trigger creation. It's just for explanation, that I need create one trigger for all dynamically created tables in future.
Any ideas?
You can use stored procedure with dynamic SQL:
CREATE PROCEDURE TriggerCreationForJournals
#XXX as nvarchar(3)
AS
BEGIN
DECLARE #sql nvarchar(max),
#triggerName nvarchar(max) = #XXX + N'_JOURNAL_UPDATE',
#objectCheck int,
#checkSQL nvarchar(max),
#params nvarchar(max) = N'#objectCheck int OUTPUT'
SELECT #checkSQL = N'SELECT #objectCheck = OBJECT_ID(N'''+#triggerName+''')'
EXEC sp_executesql #checkSQL, #params, #objectCheck = #objectCheck OUTPUT
IF #objectCheck IS NULL
BEGIN
SELECT #sql = N'
CREATE TRIGGER '+QUOTENAME(#triggerName)+' ON ['+#XXX+'_JOURNAL]
FOR UPDATE
AS
UPDATE x
SET COMPANY_ID = '''+#XXX+'''
FROM ['+#XXX+'_JOURNAL] x
INNER JOIN inserted i
ON i.ID = x.ID'
EXEC sp_executesql #sql
END
ELSE
BEGIN
PRINT 'Trigger '+QUOTENAME(#triggerName)+' already exists'
END
END
Then run this:
DECLARE #sql nvarchar(max)
SELECT #sql = (
SELECT 'EXEC TriggerCreationForJournals '''+LEFT([name],3) +''';' +CHAR(10)
FROM sys.tables
WHERE [name] LIKE '%JOURNAL'
FOR XML PATH('')
)
EXEC sp_executesql #sql
To create triggers for all tables.
In #sql there will be query like:
EXEC TriggerCreationForJournals 'AFG';
EXEC TriggerCreationForJournals 'DFG';
The purpose of stored procedure is to check if trigger on table exists - if so skip its creation, you can modify the SP to drop them if exists.
The second part is a creation of script and running the SP for all tables you need.
Hope, this answer helps you with your questions.

Set a cursor on a table inside a table variable

All,
Trying to set a cursor on a table value inside a table variable, but it does not work. can anyone comment on how I can fix this?
** the code below is called from another stored procedure which provides the value for the tablename variable **
ALTER PROCEDURE [dbo].[usrSetLTDNormDist]
-- Add the parameters for the stored procedure here
#TableName Sysname,
---...
DECLARE #SQLCommand1 NVARCHAR(MAX) = N'
Set #RecCursor1 = Cursor For
Select [Volume], [TRANSDATE] from #TableName'
EXECUTE dbo.sp_executesql #sqlCommand1
-- Open Cursor
Open #RecCursor1
Fetch Next From #RecCursor1
Into #Volume, #TransDate
---...
Add PRINT #SQLCommand1 between the DECLARE and EXECUTE statements to review what is actually being executed. Based on your code snippet, you will see
Set #RecCursor1 = Cursor For
Select [Volume], [TRANSDATE] from #TableName
...that is, the value you set in #TableName is not automagically added to the script. Here's the way I write these things:
DECLARE #SQLCommand1 NVARCHAR(MAX)
SET #SQLCommand1 = replace(N'
Set #RecCursor1 = Cursor For
Select [Volume], [TRANSDATE] from <#TableName>'
,'<#TableName>', #TableName)
PRINT #SQLCommand1
EXECUTE dbo.sp_executesql #sqlCommand1
I use the < > characters to make the replaced values stand out.
This script demonstrates the general technique:
create table T (ID int not null)
go
insert into T(ID) values (99)
go
declare #TableName sysname
declare #ID int
set #TableName = 'T'
declare #SQL nvarchar(max) = N'declare boris cursor for select ID from ' +
QUOTENAME(#TableName)
exec sp_executesql #SQL
open boris
fetch next from boris into #ID
while ##FETCH_STATUS = 0
begin
print #ID
fetch next from boris into #ID
end
close boris
deallocate boris
Producing this output:
(1 row(s) affected)
99
However, I will offer my usual caution - if you're in a situation where you want to operate against multiple tables in the same way, this is usually a sign of a broken data model. Usually there ought to be a single table with additional columns containing data that serves to differentiate the values.

Setting the field selection of a SELECT statement with the Stored Procedure's Input Variable

The following simple Stored Procedure fails to return a result set, even though running this simple SELECT statement in isolation with the actual value works just fine. Any ideas why?
ALTER PROCEDURE [dbo].[PageHeadingGetText]
#PageType nvarchar(100)
AS
BEGIN
SET NOCOUNT ON;
SELECT #PageType FROM [dbo].[PageHeadingText]
END
You didn't ask directly but in the title you say "Setting the field selection of a SELECT".
You have to use dynamic SQL to dynamically build a statement :
ALTER PROCEDURE [dbo].[PageHeadingGetText]
#columns nvarchar(max)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sqlCommand NVARCHAR(MAX)
SET #sqlCommand = 'SELECT ' + #columns + ' FROM [dbo].[PageHeadingText]'
EXECUTE sp_executesql #sqlCommand
END

Create temp table from provided variable column names

I want to create a temporary table, in which the columns will be those which I provide as parameter, separated by a delimiter.
For example, if the column names are: id, name, address..the respective table should contain the same amount and header names of the columns. Similarly, next time the column number and names could vary.
Any help in this regard?
Try this :-
CREATE PROCEDURE GenerateTempTable
#tableName as nvarchar(max),
#Col1 as nvarchar(255),
#Col2 as nvarchar(255)
AS
BEGIN
Declare #sql nvarchar(max)
set #sql='CREATE TABLE #'+ #tableName + '
('+ #col1+ ' nvarchar(255),'+
#col2 + ' nvarchar(255)
)'
-- Select #sql Check the DDL
EXECUTE sp_executesql #sql,
N'#tableName nvarchar(max),#Col1 nvarchar(255),#Col2 nvarchar(255)',
#tableName = #tableName,#Col1=#Col1,#Col2=#Col2
END
The problem with the above query is temp table is created with the dynamic block query therefore it cannot be accessed after the block . In order to access the table outside the scope then you need to create global temp table ##
Edit :-
An example with Global Temp Tables and static table name
ALTER PROCEDURE GenerateTable
#Col1 as nvarchar(255),
#Col2 as nvarchar(255)
AS
BEGIN
Declare #sql nvarchar(max)
If object_id('tempdb..##TempTable') is not null
Drop table ##TempTable
set #sql='CREATE TABLE ##TempTable
('+ #col1+ ' nvarchar(255),'+
#col2 + ' nvarchar(255)
)'
-- Select #sql Check the DDL
EXECUTE sp_executesql #sql,
N'#Col1 nvarchar(255),#Col2 nvarchar(255)',
#Col1=#Col1,#Col2=#Col2
END
To execute the SP the sql is :-
Declare #tableName varchar(max),
#Col1 varchar(70),
#Col2 varchar(70)
Exec GenerateTable #col1='ColA',#Col2='ColB'
Edit 2:-
If you are sure that the number of parameters wont exceed x values ( Say 5) .Then you can create 5 default parameter .Check this link for further details.
Could you not build a table out of a distinct list from wherever these "Dynamic Field Names" live... Then push that in as a string list... Like... I built a table with colors then got a field of names and now am going to push it into a string that can be used to build out the table headers... no limit to quantity...
SELECT #Fields = coalesce(#Fields + ',', '') + convert(varchar(50),[name])
FROM #TempCols
WHERE column_id > 1
ORDER BY column_id
Where Column_ID is just a Windowed ROW_Number...
I don't agree with the notion of its not possible ever. There is always a way, we may not see it now but there is always a method that can be nested or abused to bend any rule to what we need.