Update Statement in a Stored Procedure - sql

I have a stored Procedure called Active and the code is:
CREATE PROCEDURE dbo.Active
(
#ID INT ,
#Source VARCHAR(25)
)
AS
BEGIN
DECLARE #SQL NVARCHAR(MAX)
DECLARE #SchemaName SYSNAME
DECLARE #TableName SYSNAME
DECLARE #DatabaseName SYSNAME
DECLARE #BR CHAR(2)
SET #BR = CHAR(13) + CHAR(10)
SELECT #SchemaName = Source_Schema ,
#TableName = Source_Table ,
#DatabaseName = Source_Database
FROM Source
WHERE ID = #ID
SET #SQL = 'UPDATE Source_Table' + #BR
+ 'SET __ACTIVE = CASE WHEN rn = 1 THEN 1 ELSE 0 END' + #BR
+ 'FROM ( ' + #BR + 'SELECT ROW_NUMBER() OVER (PARTITION BY '
+ #Source + ' ORDER BY __REC_ID DESC) AS rn
, * FROM ' + #DatabaseName + '.' + #SchemaName + '.' + #TableName
+ #BR + ') Source_Table' + #BR
EXEC #SQL
END
The problem is I am using thsi procedure in another procedure so Everytime that Procedure runs this procedure also runs and does the update to whole table.
The main reason for that update is to check for the duplicates on the table and set the duplicates to 0 and remaining to 1.
I dont want to run this update for whole table but I want the update to run only for Active duplicates.
Is there a way to do it?

To reiterate your issue. You are calling the above stored procedure from another stored procedure. I assume that the parent procedure is what is determining what you call "Active duplicates". If that is the case, then you have a few options:
1) Temp table, have the first procedure create a global temporary table and use it in nested procedure. Make sure to clean up after.
--Base procedure creates global temp table with proper values;
SELECT ID
INTO ##ActiveDups
FROM DUPTABLE
WHERE SOMECONDITION = SOMECONDITION
--Join global temp table on query
SET #SQL = 'UPDATE Source_Table' + #BR
+ 'SET __ACTIVE = CASE WHEN rn = 1 THEN 1 ELSE 0 END' + #BR
+ 'FROM ( ' + #BR + 'SELECT ROW_NUMBER() OVER (PARTITION BY '
+ #Source + ' ORDER BY __REC_ID DESC) AS rn
, * FROM ' + #DatabaseName + '.' + #SchemaName + '.' + #TableName
+ #BR + ') Source_Table' + #BR
+ ' INNER JOIN ##ActiveDups ad ON ad.ID = Source_Table.ID'
--Drop global temp table
DROP TABLE ##ActiveDups
2) Parameter, pass a comma separated list to the nested procedure and filter with IN or EXISTS clause. Not very scalable. (See added parameter and last line of query)
CREATE PROCEDURE dbo.Active
(
#ID INT ,
#Source VARCHAR(25),
#List VARCHAR(MAX)
)
--...
SET #SQL = 'UPDATE Source_Table' + #BR
+ 'SET __ACTIVE = CASE WHEN rn = 1 THEN 1 ELSE 0 END' + #BR
+ 'FROM ( ' + #BR + 'SELECT ROW_NUMBER() OVER (PARTITION BY '
+ #Source + ' ORDER BY __REC_ID DESC) AS rn
, * FROM ' + #DatabaseName + '.' + #SchemaName + '.' + #TableName
+ #BR + ') Source_Table' + #BR
+ ' WHERE SOMECONDITION IN ' #List
3) Add logic to your dynamic SQL to fetch the proper results. (See last line, which was appended. I cannot determine for you what that logic may be.)
SET #SQL = 'UPDATE Source_Table' + #BR
+ 'SET __ACTIVE = CASE WHEN rn = 1 THEN 1 ELSE 0 END' + #BR
+ 'FROM ( ' + #BR + 'SELECT ROW_NUMBER() OVER (PARTITION BY '
+ #Source + ' ORDER BY __REC_ID DESC) AS rn
, * FROM ' + #DatabaseName + '.' + #SchemaName + '.' + #TableName
+ #BR + ') Source_Table' + #BR
+ ' WHERE SOMECONDITION = SOMECONDITION'

Related

Compare single values in SQL to identify candidate keys [duplicate]

This question already has answers here:
SQL Server: Get table primary key using sql query [duplicate]
(10 answers)
How to find out whether a table has some unique columns
(5 answers)
Closed 6 years ago.
I need to check if a column is candidate key. To make it generic, I created a stored procedure:
ALTER PROCEDURE [dbo].[CheckPK]
(
#tableName VARCHAR(100),
#pk VARCHAR(100)
)
AS
PRINT 'Checking for candidate key ' + #pk + ' for table: ' + #tableName
DECLARE #sql NVARCHAR(4000)
SET #sql = 'select count(distinct ([' + #pk + '])) as tot_pk from ' + #tableName + ' select count (*) as tot_real from ' + #tableName
EXEC sp_executesql #sql
Which works fine. What I have to do is verify that the two selected values are the same.
QUESTION: is it possible to add an if(tot_pk = tot_real) type of condition?
I am a newbie in SQL, so I apologise if this question seems trivial. Thank you
Try this code. Maybe is that you need.
I added an optional parameter #Schema.
CODE
--EXEC [dbo].[CheckPK] 'name of table','name of column', 'schema is optional'
ALTER PROCEDURE [dbo].[CheckPK]
(
#tableName VARCHAR(100)
, #pk VARCHAR(100)
, #Schema VARCHAR(100) = NULL
)
AS
BEGIN
BEGIN TRY
PRINT 'Checking primary key ' + #pk + ' for table: ' + #tableName
DECLARE #sql NVARCHAR(4000)
SET #sql = 'select count(distinct ([' + #pk + '])) as tot_pk from '
+ ISNULL(#Schema + '.', '') + #tableName + ' select count (*) as tot_real from ' + ISNULL(#Schema + '.', '') + #tableName
EXEC sp_executesql #sql
IF EXISTS (
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + CONSTRAINT_NAME), 'IsPrimaryKey') = 1
AND TABLE_NAME = #tableName
AND TABLE_SCHEMA = ISNULL(#Schema, TABLE_SCHEMA)
AND COLUMN_NAME = #pk
)
SELECT #pk + ' IS A PRYMARY KEY'
ELSE
SELECT #pk + ' IS NOT A PRYMARY KEY'
END TRY
BEGIN CATCH
SELECT 'An error has occurred. Verify that ''' + #tableName + ''' it is a table and has the correct schema and ''' + #pk + ''' is a valid column of the table'
END CATCH
END

Return Row Count Using Dynamic SQL

I'm trying to run the following Dynamic SQL statement:
#Tbl, #Fld, and #LookupValue have all been set according to Table to search, Field (Or Column) to search and column value to compare.
DECLARE #Sql AS VARCHAR(500)
SET #Sql = 'SELECT COUNT(*)
FROM ' + #Tbl +
' WITH (NOLOCK)
WHERE ' + #Fld + ' = ''' + #LookupValue + ''''
EXEC(#Sql)
I want to store the result into a variable so I can check to see if there are any returned rows. This statement is in the middle of a WHILE construct that is checking several tables and fields.
If records are found, then I want to display:
SET #Sql = 'SELECT ' + #Fld +
' FROM ' + #Tbl +
' WITH (NOLOCK)
WHERE ' + #Fld + ' = ''' + #LookupValue + ''''
EXEC(#Sql)
Yes, you can store it in a typed variable and use sp_executesql like
DECLARE #Sql AS NVARCHAR(500);
DECLARE #cnt INT;
SET #Sql = 'SELECT #cnt = COUNT(*)
FROM ' + #Tbl +
' WITH (NOLOCK)
WHERE ' + #Fld + ' = ''' + #LookupValue + '''';
EXEC sp_executesql #Sql, N'#cnt INT OUTPUT', #cnt OUTPUT;
SELECT #cnt;
you can create a temporary table and store the count value.
if object_id('tempdb.#mycount') is null
create table #mycount ( countVal int);
DECLARE #Sql AS VARCHAR(500)
SET #Sql = 'INSERT INTO #mycount
SELECT COUNT(*)
FROM ' + #Tbl +
' WITH (NOLOCK)
WHERE ' + #Fld + ' = ''' + #LookupValue + ''''
EXEC(#Sql)
select countVal from #mycount
-- once the temp table usage is done, you can delete it
drop table #mycount

Table Columns as parameters to Stored Procedure [duplicate]

I have created a procedure in dynamic SQL which has a select statement and the code looks like:
ALTER PROCEDURE cagroup (
#DataID INT ,
#days INT ,
#GName VARCHAR(50) ,
#T_ID INT ,
#Act BIT ,
#Key VARBINARY(16)
)
AS
BEGIN
DECLARE #SQL NVARCHAR(MAX)
DECLARE #SchemaName SYSNAME
DECLARE #TableName SYSNAME
DECLARE #DatabaseName SYSNAME
DECLARE #BR CHAR(2)
SET #BR = CHAR(13) + CHAR(10)
SELECT #SchemaName = Source_Schema ,
#TableName = Source_Table ,
#DatabaseName = Source_Database
FROM Source
WHERE ID = #DataID
SET #SQL = 'SELECT ' + #GName + ' AS GrName ,' + #BR
+ #T_ID + ' AS To_ID ,' + #BR
+ #DataID + ' AS DataSoID ,' + #BR
+ #Act + ' AS Active ,' + #BR
+ Key + ' AS key' + #BR
+ 'R_ID AS S_R_ID' + #BR
+ 'FROM' + #DatabaseName + '.'
+ #SchemaName + '.'
+ #TableName + ' t' + #BR
+ 'LEFT OUTER JOIN Gro g ON g.GName = '
+ #GName + #BR + 'AND g.Data_ID] =' + #DataID + #BR
+ 't.[I_DATE] > GETDATE() -' + #days + #BR
+ 'g.GName IS NULL
AND ' + #GName + ' IS NOT NULL
AND t.[Act] = 1' + #BR
PRINT (#SQL)
END
When I am executing this procedure with this statement:
Exec dbo.cagroup 1,10,'[Gro]',1,1,NULL
I am getting the following error.
Msg 245, Level 16, State 1, Procedurecagroup, Line 33
Conversion failed when converting the nvarchar value 'SELECT [Gro] AS GName ,
' to data type int.
Where am I doing wrong?
You need to CAST all numbers to nvarchar in the concatenation.
There is no implicit VBA style conversion to string. In SQL Server data type precedence means ints are higher then nvarchar: so the whole string is trying to be CAST to int.
SET #SQL = 'SELECT ' + #GName + ' AS GrName ,' + #BR
+ CAST(#T_ID AS nvarchar(10)) + ' AS To_ID ,' ...
Edit: Will A has a good point: watch for NULLs!
If you have to build this kind of dynamic SQL, it is better to get the column information from the meta-data than to pass it around.
Select * from Information_Schema.Columns Where Table_name=#TableName
The you have to write an ugly cursor to build the SQL. Expect performance problems. I do lots of this during development to write code for me, but I don't dare run it in production.

Dynamic SQL error converting nvarchar to int

I have created a procedure in dynamic SQL which has a select statement and the code looks like:
ALTER PROCEDURE cagroup (
#DataID INT ,
#days INT ,
#GName VARCHAR(50) ,
#T_ID INT ,
#Act BIT ,
#Key VARBINARY(16)
)
AS
BEGIN
DECLARE #SQL NVARCHAR(MAX)
DECLARE #SchemaName SYSNAME
DECLARE #TableName SYSNAME
DECLARE #DatabaseName SYSNAME
DECLARE #BR CHAR(2)
SET #BR = CHAR(13) + CHAR(10)
SELECT #SchemaName = Source_Schema ,
#TableName = Source_Table ,
#DatabaseName = Source_Database
FROM Source
WHERE ID = #DataID
SET #SQL = 'SELECT ' + #GName + ' AS GrName ,' + #BR
+ #T_ID + ' AS To_ID ,' + #BR
+ #DataID + ' AS DataSoID ,' + #BR
+ #Act + ' AS Active ,' + #BR
+ Key + ' AS key' + #BR
+ 'R_ID AS S_R_ID' + #BR
+ 'FROM' + #DatabaseName + '.'
+ #SchemaName + '.'
+ #TableName + ' t' + #BR
+ 'LEFT OUTER JOIN Gro g ON g.GName = '
+ #GName + #BR + 'AND g.Data_ID] =' + #DataID + #BR
+ 't.[I_DATE] > GETDATE() -' + #days + #BR
+ 'g.GName IS NULL
AND ' + #GName + ' IS NOT NULL
AND t.[Act] = 1' + #BR
PRINT (#SQL)
END
When I am executing this procedure with this statement:
Exec dbo.cagroup 1,10,'[Gro]',1,1,NULL
I am getting the following error.
Msg 245, Level 16, State 1, Procedurecagroup, Line 33
Conversion failed when converting the nvarchar value 'SELECT [Gro] AS GName ,
' to data type int.
Where am I doing wrong?
You need to CAST all numbers to nvarchar in the concatenation.
There is no implicit VBA style conversion to string. In SQL Server data type precedence means ints are higher then nvarchar: so the whole string is trying to be CAST to int.
SET #SQL = 'SELECT ' + #GName + ' AS GrName ,' + #BR
+ CAST(#T_ID AS nvarchar(10)) + ' AS To_ID ,' ...
Edit: Will A has a good point: watch for NULLs!
If you have to build this kind of dynamic SQL, it is better to get the column information from the meta-data than to pass it around.
Select * from Information_Schema.Columns Where Table_name=#TableName
The you have to write an ugly cursor to build the SQL. Expect performance problems. I do lots of this during development to write code for me, but I don't dare run it in production.

Quick way to backup SQL SP and Functions?

I have a long list of SPs (stored procedure) and Functions in my SQL server db. I could save them one by one by right clicking and script XXX to Alter To. Is there any way in TSQL to query all SPs and functions save them to xxx.sql files?
For example, for sp_mySP1, I would like to save it to sp_mySP1.sql which is a text file. The database is too big and I would like save only SPs and functions as a backup of source codes.
In management studio; find the database, right-click, tasks, generate scripts;
next-next-next until you "Choose Object Types". Select "Stored procedures" and "User-defined functions", next, Select All; choose an output; go!
1) Right-click on your Database name in the Object Explorer
2) Select "Tasks > Generate Scripts..." from the Context menu
3) Select your Database in the list and click Next
4) Click Next on the Chose Script Options
5) In Object Types, check Stored Procedures and User-defined functions, click Next
6) Click Select All on the Stored Procedures selection screen, click Next
7) Click Select All on the Functions selection screen, click Next
8) Select 'Script to New Query Window' and click Finish
Here's a proc that will export SOME types of data.
if exists ( select * from sysobjects where name = 'ExportData_P' )
drop proc ExportData_P
go
CREATE PROC dbo.ExportData_P (
#tableName varchar(500),
#where varchar(5000) = '(1=1)'
)
AS
BEGIN
SET NOCOUNT ON
DECLARE #sql varchar(8000)
DECLARE #fieldList varchar(8000)
DECLARE #valueList varchar(8000)
SELECT #fieldList = '', #valueList = ''
DECLARE #cols TABLE ( column_name nvarchar(250), data_type varchar(250) )
DECLARE #c nvarchar(250), #data_type varchar(250)
INSERT INTO #cols
select column_name, data_type
from information_Schema.columns
where table_name = #tableName
WHILE EXISTS ( SELECT TOP 1 * FROM #cols )
BEGIN
SELECT TOP 1 #c = column_name, #data_type = data_type FROM #cols
SELECT
#fieldList = #fieldList + #c + ', ',
#valueList = #valueList + CHAR(13) + 'case when ' + #c + ' is null then ''NULL'' else '''''''' + ' +
case when #data_type in ('text','ntext','char', 'nvarchar', 'varchar' ) then
' REPLACE ( REPLACE ( REPLACE ( '
else ''
end +
'IsNull ( convert(varchar' +
( -- change this section to pass the length of varchar to convert
case when #data_type in ( 'uniqueidentifier' ) then '(50)'
when #data_type in ( 'text', 'ntext' ) then '(8000)'
else '' end
) +
', ' +
#c +
'), '''' )' + -- end is null
case when #data_type in ('text','ntext','char', 'nvarchar', 'varchar' ) then
', CHAR(39), CHAR(39)+CHAR(39) ), CHAR(13), '''' + CHAR(13) + ''''), CHAR(9), '''' + CHAR(9) + '''') '
else ''
end +
' + '''''''' end + '', '' + '
DELETE FROM #cols WHERE column_name = #c
END
SELECT #fieldList = LEFT ( #fieldList, LEN(#fieldList)-1 ),
#valueList = LEFT ( #valueList, LEN(#valueList)-1 )
SELECT #sql = 'select ''insert into ' + #tableName + ' (' + #fieldList + ') ' +
' VALUES ( ''+ ' + left ( #valueList, len(#valueList)-5) + ''') '' from ' + #tableName +
' WHERE ' + #where
-- into [#mcoe_temp_export' + #tableName + ']
print #sql
EXEC ( #sql )
--EXEC ( 'select * from [#mcoe_temp_export' + #tableName + ']' )
SET NOCOUNT OFF
END
go
Use like:
exec ExportData_P 'tablename'
you could query syscomments to get your sql object creation text, but I don't know how to save them all in separate files using just TSQL.
select * from syscomments