As a development aid, I am writing a stored procedure which creates/amends database objects from one database into another one. (The sproc takes a CSV string of object names, which it splits into individual values using XML, and therefore the QUOTED_IDENTIFIER needs to be turned on for the sproc to run.)
However, the objects being created/amended include stored procedures where QUOTED_IDENTIFIER could be turned either on or off.
According to the answer to this very similar question (which talks specifically about creating a single stored procedure) if you create/amend a stored procedure within another stored procedure, it will always use the QUOTED_IDENTIFIER values set in the "parent" sproc.
Does anybody know of a way to be able to set different QUOTED_IDENTIFIER flag values when creating/amending multiple stored procedures?
I've tried very simple code within the loop (such as the following) but as the above answer suggests, this has no effect on the result and the created/amended sproc always has QUOTED_IDENTIFIER set to ON...
IF #QUOTED = 1 -- from sys.sql_modules.uses_quoted_identifier
SET QUOTED_IDENTIFIER ON
ELSE
SET QUOTED_IDENTIFIER OFF
EXEC sp_executesql #DEFINITION -- from sys.sql_modules.definition
With many thanks to #Jeroen who sent me down the path to the solution, which is to create another development-aid stored procedure with QUOTED_IDENTIFIER set to OFF.
Within the main loop of the primary development-aid sproc it executes the definition through itself (if ON is required) or through the secondary sproc (if OFF is required).
This is a very simplified pseudo version of what I now have working...
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE DEV_AID_SUB
#DEFINITION NVARCHAR(MAX)
AS
EXEC sp_executesql #DEFINITION
---
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE DEV_AID
AS
BEGIN
WHILE #LOOP = 1
IF #QUOTED = 1
EXEC sp_executesql #DEFINITION
ELSE
EXEC DEV_AID_SUB #DEFINITION
END
END
Related
I'm trying to loop through tables and insert the records from one db to another so I want to keep things dynamic. If I run the following I get an error
DECLARE #command NVARCHAR(max) = 'SET IDENTITY_INSERT [NEW].[dbo].[TABLE] ON'
EXEC (#command)
DECLARE #command2 NVARCHAR(max) = 'Insert Into [NEW].[dbo].[TABLE] ([ID], [Description], [SiteID], [Active]) Select [ID], [Description], [SiteID], [Active] from [OLD].[dbo].[TABLE]'
EXEC (#command2)
Cannot insert explicit value for identity column in table 'TABLE' when IDENTITY_INSERT is set to OFF.
If I run the commands on their own (not as executable strings) everything works fine. My guess is that it builds #command and #command2 before execution and when it finds the problem it throws an error before trying to execute.
Does anyone have any ideas please?
SET IDENTITY_INSERT options set inside dynamic SQL will be reset when that scope exits.
You would need to set the option inside the same dynamic SQL string that is depending on it being on. This can contain multiple statements (ideally semi colon terminated)
I am trying to execute a stored procedure with EF and a variable WHERE clause.
What I first thought was this :
ALTER PROCEDURE SP
#WHEREClause VARCHAR(250)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL Varchar(8000)
SET #SQL ='Select ...' + #WHEREClause
EXEC(#SQL)
END
Problem here EF wont recognize the selected values from the stored procedure anymore.
So I think of something like that:
ALTER PROCEDURE SP
#WHEREClause VARCHAR(250)
AS
BEGIN
SET NOCOUNT ON;
Select ... FROM ... #WHEREClause
END
Anyone got an idea?
Thanks
Markus
First of all, creating a WHERE clause like this could leave you vulnerable to SQL injection. You might be able to do it safer by using LINQ to narrow down the data rather than a dynamically built WHERE.
Another way to handle it is to use the ExecuteStoreQuery method (this is Database.SqlQuery in EF5). This will allow you to load the results of the stored procedure into a POCO object. You can also parametrize the query which might make it safer, depending on how it's constructed.
I came across an interesting problem today. I was altering a stored procedure and put a select statement at the very end. It was meant to be temporary and just for working with the data. I was surprised to find out later that the statement got saved and was executing whenever the SP ran.
SET ANSI_NULLS ON
GO
-- Comments usually go here and are saved as part of the SP
ALTER PROCEDURE [dbo].[MySP]
#param INT
AS
BEGIN
--Your normal SQL statements here
END
--You can also add SQL statements here
select * from LargeTable
--You have access to the params
select #param
It makes sense that everything is saved, not just what is inside BEGIN/END, otherwise the comments and SET ANSI_NULLS, etc. would disappear. I'm a little confused with what starts where, so I have a few questions:
SET ANSI_NULLS gets saved as part of the SP. I have confirmed that each SP has its own value. How does SQL Server know to save this as part of the SP since it's not referenced before? Does it do a full scan of the current environment state, then when ALTER PROCEDURE runs it saves the state (possibly only non-default values)?
Apparently the BEGIN/END are optional and have no intrinsic meaning. Why are they even included then? They give a false sense of scope that doesn't exist. It seems to me no BEGIN/END and a GO at the end would make the most sense.
ANSI NULLS and QUOTED IDENTIFIERS are stored as metadata attributes of the stored procedure code. You can review these settings via
select * from sys.sql_modules
When a procedure is saved, these attributes are set to whatever they are for the connection through which the procedure is being saved. This can lead to irritating inconsistancies, so be wary.
As for BEGIN/END, it's exactly as #bobs says -- they denote code blocks, they do not denote the start and end of stored procedure code. (Functions, yes, procedures, no.) As you say, no BEGIN/END and a GO at the end would make the most sense is the way I've been doing it for years.
Technically, SQL will (attempt to) save everything in a batch as part of the stored procedure -- that is, all the text you submit, as broken up by GO statements (if any). If you stuck a RETURN statement right before your ad hoc queries, they'd be included in the code but never run.
The BEGIN...END defines a block of code. It doesn't define the beginning and ending of a script or procedure. But, I agree it can be confusing.
The SET QUOTED_IDENTIFIER and SET ANSI_NULLS settings are saved but not the other settings. Check out Interoperability here for more information.
Encloses a series of Transact-SQL
statements so that a group of
Transact-SQL statements can be
executed. BEGIN and END are
control-of-flow language keywords.
When SET ANSI_NULLS is ON, a SELECT statement that uses WHERE column_name = NULL returns zero rows even if there are null values in column_name. A SELECT statement that uses WHERE column_name <> NULL returns zero rows even if there are nonnull values in column_name.
When SET ANSI_NULLS is OFF, the Equals (=) and Not Equal To (<>) comparison operators do not follow the ISO standard. A SELECT statement that uses WHERE column_name = NULL returns the rows that have null values in column_name. A SELECT statement that uses WHERE column_name <> NULL returns the rows that have nonnull values in the column. Also, a SELECT statement that uses WHERE column_name <> XYZ_value returns all rows that are not XYZ_value and that are not NULL.
When SET ANSI_NULLS is ON, all comparisons against a null value evaluate to UNKNOWN. When SET ANSI_NULLS is OFF, comparisons of all data against a null value evaluate to TRUE if the data value is NULL. If SET ANSI_NULLS is not specified, the setting of the ANSI_NULLS option of the current database applies. For more information about the ANSI_NULLS database option, see ALTER DATABASE (Transact-SQL) and Setting Database Options.
SET ANSI_NULLS ON affects a comparison only if one of the operands of the comparison is either a variable that is NULL or a literal NULL. If both sides of the comparison are columns or compound expressions, the setting does not affect the comparison.
For a script to work as intended, regardless of the ANSI_NULLS database option or the setting of SET ANSI_NULLS, use IS NULL and IS NOT NULL in comparisons that might contain null values.
SET ANSI_NULLS should be set to ON for executing distributed queries.
SET ANSI_NULLS must also be ON when you are creating or changing indexes on computed columns or indexed views. If SET ANSI_NULLS is OFF, any CREATE, UPDATE, INSERT, and DELETE statements on tables with indexes on computed columns or indexed views will fail. SQL Server will return an error that lists all SET options that violate the required values. Also, when you execute a SELECT statement, if SET ANSI_NULLS is OFF, SQL Server will ignore the index values on computed columns or views and resolve the select operation as if there were no such indexes on the tables or views.
Is the nocount in SQL for each connection or each execution?
Consider the following
-- Proc to return data.
-- nocount is set to on (no row count returned)
create procedure procOne as
set nocount on
select * from myTable
If I have an application that calls procOne and then performs a SQL call such as:
DELETE from myTable where foo = bar
Will the delete statement return the number of rows deleted? I say yes.
The procedure should only set the nocount value within its execution. Please let me know if this is correct.
Thanks
Yes. It resets the value of SET variable after the procedure has completed.
If a SET statement is run in a stored procedure or trigger, the value of the SET option is restored after control is returned from the stored procedure or trigger. Also, if a SET statement is specified in a dynamic SQL string that is run by using either sp_executesql or EXECUTE, the value of the SET option is restored after control is returned from the batch specified in the dynamic SQL string.
refer http://msdn.microsoft.com/en-us/library/ms190356.aspx
It's for each execution, from the NOCOUNT docs:
The setting specified by SET NOCOUNT is in effect at execute or run time and not at parse time.
We have an Oracle application that uses a standard pattern to populate surrogate keys. We have a series of extrinsic rows (that have specific values for the surrogate keys) and other rows that have intrinsic values.
We use the following Oracle trigger snippet to determine what to do with the Surrogate key on insert:
IF :NEW.SurrogateKey IS NULL THEN
SELECT SurrogateKey_SEQ.NEXTVAL INTO :NEW.SurrogateKey FROM DUAL;
END IF;
If the supplied surrogate key is null then get a value from the nominated sequence, else pass the supplied surrogate key through to the row.
I can't seem to find an easy way to do this is T-SQL. There are all sorts of approaches, but none of which use the notion of a sequence generator like Oracle and other SQL-92 compliant DBs do.
Anybody know of a really efficient way to do this in SQL Server T-SQL? By the way, we're using SQL Server 2008 if that's any help.
You may want to look at IDENTITY. This gives you a column for which the value will be determined when you insert the row.
This may mean that you have to insert the row, and determine the value afterwards, using SCOPE_IDENTITY().
There is also an article on simulating Oracle Sequences in SQL Server here: http://www.sqlmag.com/Articles/ArticleID/46900/46900.html?Ad=1
Identity is one approach, although it will generate unique identifiers at a per table level.
Another approach is to use unique identifiers, in particualr using NewSequantialID() that ensues the generated id is always bigger than the last. The problem with this approach is you are no longer dealing with integers.
The closest way to emulate the oracle method is to have a separate table with a counter field, and then write a user defined function that queries this field, increments it, and returns the value.
Here is a way to do it using a table to store your last sequence number. The stored proc is very simple, most of the stuff in there is because I'm lazy and don't like surprises should I forget something so...here it is:
----- Create the sequence value table.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SequenceTbl]
(
[CurrentValue] [bigint]
) ON [PRIMARY]
GO
-----------------Create the stored procedure
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[sp_NextInSequence](#SkipCount BigInt = 1)
AS
BEGIN
BEGIN TRANSACTION
DECLARE #NextInSequence BigInt;
IF NOT EXISTS
(
SELECT
CurrentValue
FROM
SequenceTbl
)
INSERT INTO SequenceTbl (CurrentValue) VALUES (0);
SELECT TOP 1
#NextInSequence = ISNULL(CurrentValue, 0) + 1
FROM
SequenceTbl WITH (HoldLock);
UPDATE SequenceTbl WITH (UPDLOCK)
SET CurrentValue = #NextInSequence + (#SkipCount - 1);
COMMIT TRANSACTION
RETURN #NextInSequence
END;
GO
--------Use the stored procedure in Sql Manager to retrive a test value.
declare #NextInSequence BigInt
exec #NextInSequence = sp_NextInSequence;
--exec #NextInSequence = sp_NextInSequence <skipcount>;
select NextInSequence = #NextInSequence;
-----Show the current table value.
select * from SequenceTbl;
The astute will notice that there is a parameter (optional) for the stored proc. This is to allow the caller to reserve a block of ID's in the instance that the caller has more than one record that needs a unique id - using the SkipCount, the caller need make only a single call for however many IDs are needed.
The entire "IF EXISTS...INSERT INTO..." block can be removed if you remember to insert a record when the table is created. If you also remember to insert that record with a value (your seed value - a number which will never be used as an ID), you can also remove the ISNULL(...) portion of the select and just use CurrentValue + 1.
Now, before anyone makes a comment, please note that I am a software engineer, not a dba! So, any constructive criticism concerning the use of "Top 1", "With (HoldLock)" and "With (UPDLock)" is welcome. I don't know how well this will scale but this works OK for me so far...