Data purging Delete statement formation - sql

I was just writing a stored procedure and I am stuck badly at one point.
Basically my stored procedure looks like this:
CREATE PROCEDURE [dbo].[DELETEGUIDTESTNEW1]
(#IpApplicationNumber NVARCHAR(50) = NULL)
AS
BEGIN
DECLARE #ApplicationNumber NVARCHAR(20)
SET #ApplicationNumber = (SELECT APPLICATIONNUMBER
FROM CUSTOMERROLE
WHERE CUSTOMERNUMBER = #IpCustomerNumber
AND CUSTOMERVERSIONNUMBER = #IpCustomerVersion)
-- In between I am doing business operation--------------------
INSERT INTO dbo.DeleteTest1(Statements)
VALUES ('Delete from '+#GuidTableName+' where ApplicationNumber =' + #ApplicationNumber)
I will get my parameter at runtime but actual issue is I want to form my delete statements before getting application number and I want form my delete statements in such a way that when I will get my application number I will fetch all delete statement from table and replace #ApplicationNumber by actual application number and will delete records from database.
So basically I want to form delete statements with application number as template and delete records at runtime.
Please help!

Well I have found solution to db purging. To handle runtime GUID situation I published stored procedure from stored procedure.
SELECT #GuidPrimaryTableSpace = #GuidPrimaryTableSpace + DeleteGuidStatement + ';'+ CHAR(13) + CHAR(10)
FROM ##Purge_GuidForeignKeyTablePurgeStatements
SELECT #GuidForeignKeyTableSpace = #GuidForeignKeyTableSpace +'Insert Into #AddressRecordsToPurge (GuidValue, GuidColumn) ( '+ SelectGuidStatement +');'+ CHAR(13) + CHAR(10)
FROM ##Purge_GuidPrimaryTablePurgeStatements
SELECT #DeleteGuidStatementSpace = #DeleteGuidStatementSpace + DeleteGuidValueStatement + ';'+ CHAR(13) + CHAR(10)
FROM ##Purge_GuidTableNames
SET #createProcedureCmd = 'CREATE PROCEDURE MyProc' + ' (#ApplicationNum nvarchar(50),#CustomerNumber nvarchar(50),#CustomerVersionNumber nvarchar(50)) AS ' + ' BEGIN '+
' DECLARE #ApplicationNumber nvarchar(50); SET #ApplicationNumber = #ApplicationNum;
DECLARE #AddressRecordsToPurge TABLE
(
RowID INT NOT NULL PRIMARY KEY IDENTITY(1,1),
GUIDValue Nvarchar(max),
GUIDColumn Nvarchar(max)
)'+ CHAR(13) + CHAR(10) + #GuidForeignKeyTableSpace + #GuidPrimaryTableSpace + #DeleteGuidStatementSpace +' END'
EXEC(#createProcedureCmd)
So here I am forming all select statement first and publishing stored procedure. At runtime when it will hit my published stored procedure, I will first find all guids in temp table and then start my delete.
Thank you anyways for all inputs.

Related

Programmatically set the permissions on a table

I want to programmatically set the permissions (i.e. GRANT) on a newly created table. I was hoping to get SQL Server to show me the script for that by going to another table in the database and doing a right-click and then "Script Table as" but I don't see the option for GRANT underneath that.
Is it possible to get SQL Server to show me the script for this?
Look around some more. The simple version is to use the dialog where you set permissions. E.g.,
A more general and advanced approach - with far more options - is to use the script feature at the database level. On your database, rt click and select , , and then run through the wizard to select your table and the scripting options you want. Be sure to click the Advanced button in the scripting options tab - where you will see "object-level permissions" (off by default).
Too long to comment.
GRANT <n> ON YourDatabase.YourSchema.YourTable TO YourSpecificUser
In this case, since it's a table <n> can be one of the following:
DELETE
INSERT
REFERENCES
SELECT
UPDATE
Note, if a user has a fixed database role, they could have more access than you explicitly grant them. Read more about GRANT Object Permissions.
Of note, to return a list of permissions on a table, you can use sp_table_privileges
sp_table_privileges #table_name = 'YourTable'
You can capture these results and then loop through them to build a dynamic sql query.
Replace the script below with your TableName and what ever your NewTableName is. When you are satisfied with the print out, you can uncomment the exec(#sql) to execute the code that's printed.
if object_id('tempdb..#priv') is not null
drop table #priv
create table #priv( ID int identity (1,1)
,TABLE_QUALIFIER varchar(64)
,TABLE_OWNER VARCHAR(64)
,TABLE_NAME VARCHAR(64)
,GRANTOR VARCHAR(64)
,GRANTEE VARCHAR(64)
,PRIVILEGE VARCHAR(64)
,IS_GRANTABLE VARCHAR(8))
insert into #priv
exec sp_table_privileges #table_name = 'YourTableName'
declare #i int = 1
declare #max int = (select max(id) from #priv)
declare #sql varchar(max) = ''
while (#i <= #max)
begin
set #sql = #sql + (select ' GRANT ' + stuff(PRIVILEGE,1,0,' ') + ' ON ' + stuff(TABLE_NAME,1,0,' ') + ' TO ' + stuff(GRANTEE,1,0,' ') + char(13) + ' GO ' + char(13) from #priv where ID = #i)
set #i = #i + 1
end
print(#sql)
set #sql = replace(#sql,'YourTableName','NewTableName')
print(#sql)
--exec(#sql)

Pass the Multiple quotes around #variable wherever single quote is there

Below is my procedure. It is working fine.
Create PROCEDURE [dbo].[spCompanyName]
(
#CompanyName VARCHAR(100))
AS
Begin
DECLARE #sql VARCHAR(MAX)
SET #sql = ' Select EmpID,CompanyName FROM Employee' + CHAR(13) + CHAR(10)
IF len(#CompanyName) > 0
BEGIN
SET #sql = #sql + ' Where (RTRIM(LTRIM(CompanyName)) like ''' + #CompanyName + '%'') ' + char(13) + char(10)
END
PRINT #SQL
EXEC(#sql)
End
exec spCompanyName #CompanyName='So Unique, formerly Sofia''''s'
I need Wherever single quote is there in companyname,if I pass 8 quotes in single quotes I need output.above procedure where do I need to change.
Eg:
exec spCompanyName #CompanyName='So Unique, formerly Sofia''''''''s'
exec spCompanyName #CompanyName='Absolute''''''''s,Strategy''''''''s'
Don't think "I'll throw away all of the useful features of using parameters to separate data from code and start manually trying to protect strings" - keep using parameters.
Rather than
EXEC(#sql)
Have:
EXEC sp_executesql #sql,N'#CompanyName varchar(100)',#CompanyName = #CompanyName
And change:
SET #sql = #sql + ' Where (RTRIM(LTRIM(CompanyName)) like ''' + #CompanyName + '%'') ' + char(13) + char(10)
to:
SET #sql = #sql + ' Where (RTRIM(LTRIM(CompanyName)) like #CompanyName + ''%'') ' + char(13) + char(10)
Or, in the alternative, consider just writing a normal query, no dynamic SQL:
Create PROCEDURE [dbo].[spCompanyName]
(
#CompanyName VARCHAR(100))
WITH RECOMPILE
AS
Begin
Select EmpID,CompanyName FROM Employee
Where RTRIM(LTRIM(CompanyName)) like #CompanyName + '%' or
#CompanyName is null
End
Assuming you're using SQL Server 2008 (with particular patch levels) or later, as specified in Erland Sommarskog's Dynamic Search Conditions in T-SQL
If you are going to create a new stored procedure for this feature then you can have this in much better way then dynamic.
You should execute different select queries based on if CompanyName is passed or not.
You can simply the stored procedure as following.
Create PROCEDURE [dbo].[spCompanyName]
(
#CompanyName VARCHAR(100))
AS
Begin
IF LEN(#CompanyName) > 0
BEGIN
Select EmpID,CompanyName FROM Employee WHERE RTRIM(LTRIM(CompanyName)) like '' + #CompanyName + '%'
END
ELSE
BEGIN
Select EmpID,CompanyName FROM Employee
END
END
I am not sure why you need to pass so many single quotes in the parameter value but to me it looks like you can execute the procedure with following simple way.
EXEC spCompanyName #CompanyName='So Unique, formerly Sofia''s'
EXEC spCompanyName #CompanyName='Absolute''s,Strategy''s'
This should help you finding your solution.

How to Create DELETE Statement Stored Procedure Using TableName, ColumnName, and ColumnValue as Passing Parameters

Here is what i'm trying to do. I'm trying to create a stored procedure where I could just enter the name of the table, column, and column value and it will delete any records associated with that value in that table. Is there a simple way to do this? I don't know too much about SQL and still learning about it.
Here is what I have so far.
ALTER PROCEDURE [dbo].[name of stored procedure]
#TABLE_NAME varchar(50),
#COLUMN_NAME varchar(50),
#VALUE varchar(5)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #RowsDeleted int;
DECLARE #sql VARCHAR(500);
SET #sql = 'DELETE FROM (name of table).' + #TABLE_NAME + ' WHERE ' + #COLUMN_NAME + '=' + '#VALUE'
EXEC(#sql)
SET #RowsDeleted=##ROWCOUNT
END
GO
Couple issues
First, you don't need (name of table)
SET #sql = 'DELETE FROM ' + #TABLE_NAME + etc.
In general you should try to include the appropriate schema prefix
SET #sql = 'DELETE FROM dbo.' + #TABLE_NAME + etc.
And in case your table name has special characters perhaps it should be enclosed in brackets
SET #sql = 'DELETE FROM dbo.[' + #TABLE_NAME + ']' + etc.
Since #Value is a string, you must surround it with single quotes when computing the value for #SQL. To insert a single quote into a string you have to escape it by using two single quotes, like this:
SET #SQL = 'DELETE FROM dbo.[' + #TABLE_NAME + '] WHERE [' + #COLUMN_NAME + '] = '''' + #VALUE + ''''
If #VALUE itself contains a single quote, this whole thing will break, so you need to escape that as well
SET #SQL = 'DELETE FROM dbo.[' + #TABLE_NAME + '] WHERE [' + #COLUMN_NAME + '] = '''' + REPLACE(#VALUE,'''','''''') + ''''
Also, ##ROWCOUNT will not populate from EXEC. If you want to be able to read ##ROWCOUNT, use sp_ExecuteSQL instead
EXEC sp_ExecuteSql #SQL
And finally, let me editorialize for a minute--
This sort of stored procedure is not a great idea. I know it seems pretty cool because it is flexible, and that kind of thinking is usually smart when it comes to other languages, but in the database world this approach causes problems, e.g. there are security issues (e.g. injection, and the fact that you need elevated privileges to call sp_executeSql) and there issues with precompilation/performance (because the SQL isn't known ahead of time, SQL Server will need to generate a new query plan each and every time you call this) and since the caller can supply any value for table and column name you have no idea whether this delete statement will be efficient and use indexes or if it will cause a huge performance issue because the table is large and the column is not indexed.
The proper approach is to have a series of appropriate stored procedures with strongly-typed inputs that are specific to each data use case where you need to delete based on criteria. Database engineers should not be trying to make things flexible; you should be forcing people to think through what exactly they are going to need, and implement that and only that. That is the only way to ensure people are following the rules, keeping R/I intact, efficient use of indexes, etc.
Yes, this may seem like repetitive and redundant work, but c'est la vie. There are tools available to generate the code for CRUD operations if you don't like the extra typing.
In addition to some of the information John Wu provided you have to worry about data types and ##ROWCOUNT may not be accurate if there are triggers on your tables and things..... You can get around both of those issues though by casting to nvarchar() and using OUTPUT clause with a temp table to do the COUNT().
So just for fun here is a way you can do it:
CREATE PROCEDURE dbo.[ProcName]
#TableName SYSNAME
,#ColumnName SYSNAME
,#Value NVARCHAR(MAX)
,#RecordCount INT OUTPUT
AS
BEGIN
DECLARE #SQL NVARCHAR(1000)
SET #SQL = N'IF OBJECT_ID(''tempdb..#DeletedOutput'') IS NOT NULL
BEGIN
DROP TABLE #DeletedOutput
END
CREATE TABLE #DeletedOutput (
ID INT IDENTITY(1,1)
ColumnValue NVARCHAR(MAX)
)
DELETE FROM dbo.' + QUOTENAME(#TableName) + '
OUTPUT deleted.' + QUOTENAME(#ColumnName) + ' INTO #DeletedOutput (ColumnValue)
WHERE CAST(' + QUOTENAME(#ColumnName) + ' AS NVARCHAR(MAX)) = ' + CHAR(39) + #Value + CHAR(39) + '
SELECT #RecordCountOUT = COUNT(ID) FROM #DeletedOutput
IF OBJECT_ID(''tempdb..#DeletedOutput'') IS NOT NULL
BEGIN
DROP TABLE #DeletedOutput
END'
DECLARE #ParmDefinition NVARCHAR(200) = N'#RecordCountOUT INT OUTPUT'
EXECUTE sp_executesql #SQL, #ParmDefinition, #RecordCountOUT = #RecordCount OUTPUT
END
So the use of QOUTENAME will help against the injection attack but not be perfect. And I use CHAR(39) instead of the escape sequence for a single quote on value because I find it easier when string building at that point.... By using Parameter OUTPUT from sp_executesql you can still return your count.
Keep in mind just because you can do something in SQL doesn't always mean you should.

SQL merge functionality without specifying column names

I'm doing a SQLBulkCopy from my web app and inserting the records into a staging table. This is my first time working with staging tables. The live table that will be accepting the data has about 200 fields and can change into the future. When this change occurs I didn't want to have to re-write the merge statement.
I came up with this SQL that mimics the merge functionality, but doesn't require me to spell out the table columns. I am not an SQL expert and wanted someone that is to take a look and let me know if you see any problems that could arise by using this SQL because I haven't seen any examples of this and many people searching.
Note that records in the staging table that have a null id field are to be inserted.
-- set the table names, primary key field & vars to hold query parts
DECLARE #LiveTable varchar(20) = 'Test'
DECLARE #StagingTable varchar(20) = 'TestStaging'
DECLARE #PKField varchar(20) = 'TestPK'
DECLARE #SQLSet nvarchar(MAX) = ''
DECLARE #SQLInsertFields nvarchar(MAX) = ''
-- get comma delimited field names
DECLARE #Fields nvarchar(MAX) = (SELECT dbo.fn_GetCommaDelimitedFieldNames(#LiveTable))
-- loop through fields generating set clause of query to execute
WHILE LEN(#Fields) > 0
BEGIN
DECLARE #Field varchar(50) = left(#Fields, CHARINDEX(',', #Fields+',')-1)
IF #Field <> #PKField -- the primary key field cannot be updated
BEGIN
SET #SQLSet += ', ' + #LiveTable + '.' + #Field + ' = ' + #StagingTable + '.' + #Field
SET #SQLInsertFields += ', ' + #Field
END
SET #Fields = STUFF(#Fields, 1, CHARINDEX(',', #Fields+','), '')
END
-- remove the leading comma
SET #SQLSet = SUBSTRING(#SQLSet,3,LEN(#SQLSet))
SET #SQLInsertFields = SUBSTRING(#SQLInsertFields,3,LEN(#SQLInsertFields))
-- update records from staging table where primary key is provided
DECLARE #SQL nvarchar(MAX) = N'UPDATE ' + #LiveTable +
' SET ' + #SQLSet +
' FROM ' + #LiveTable +
' INNER JOIN ' + #StagingTable +
' ON ' + #LiveTable + '.' + #PKField + ' = ' + #StagingTable + '.' + #PKField
-- insert records from staging table where primary key is null
SET #SQL += '; INSERT INTO ' + #LiveTable + ' (' + #SQLInsertFields + ') SELECT ' + #SQLInsertFields + ' FROM ' + #StagingTable + ' WHERE ' + #PKField + ' IS NULL'
-- delete the records from the staging table
SET #SQL += '; DELETE FROM ' + #StagingTable
-- execute the sql statement to update existing records and insert new records
exec sp_executesql #SQL;
If anyone see's any issues with performance or anything else, I appreciate the insight.
Don't do this. Really. You're working very hard to avoid a rare problem that you probably won't handle correctly when the time comes.
If the target table changes, how do you know it will change in such a way that your fancy dynamic SQL will work correctly? How can you be sure it won't seem to work -- i.e. will work, syntactically -- but actually do the wrong thing? If and when the target table changes, won't you have to change your application, and the staging table too? With all that in the air, what's adding one more SET clause?
In the meanwhile, how can anyone be expected to read that gobbledygook (not your fault, really, that's SQL's syntax)? A bog-standard insert statement would be very clear and dependable.
And fast. SQL Server can't optimize your dynamic query. You used bcp for efficiency, and now you're defeating it with well meaning futureproofingness.

Don't display dynamic query in result

Is it possible to hide a dynamic query from the result sets provided from a Stored Procedure?
I am using the ##rowcount of the dynamic query to set a variable that is used to determine whether another query runs or not.
The other query is used by code that I cannot change - hence why I am changing the Stored Procedure. The dynamic query returns as the first result set from the Stored Procedure is now the result of the dynamic query which currently is "breaking" the calling code.
Thanks in advance
I have managed to solve this by inserting the result of the dynamic query into a temporary table and then retrieving the rowcount from the temporary table.
-- Create query
declare #query nvarchar(max)
set #query = 'select ' + #entityname + 'id from ' + #entityname + ' where ' + #entityname + 'id = ' + cast(#entityid as nvarchar(100))
-- Insert into to temp table - no new result set displayed!
declare #tbl table (EntityID int not null primary key)
insert into #tbl
exec (#query)
-- Retrieve variable from temporary table
declare #count int
select #count = count(*) from #tbl
Above is the code I ended up using.
Try wrapping the dynamic query like this:
Set #query = 'SELECT COUNT(*) FROM (' + #Query + ') t'