Quantcast
Channel: SQL Server Database Engine forum
Viewing all 15930 articles
Browse latest View live

Non Clustered Index and Singleton Lookup - Where is it occuring

$
0
0

Fellow SQLers,

I was doing some reviewing on the internals of SQL Indexing and what happens inside the engine.

My question is about a Singleton lookup on a non clustered index.

So, sql goes thru the b true, pulls the intermdiate page into memory (data cache).

Then gets to the page with the rows. It then does a binary search to get the row.

Where is that binary search occuring? Is that page being pulled into memory (data cache) to do the binary search or is it being done before the page pull?

thanks,

MG


How to verify Quorum Configuration in Win Server 2016?

$
0
0

Get-ClusterQuorum |fl

Gives

Cluster        : ClusterName
QuorumResource : File Share Witness
QuorumType     : Majority

----

I was expecting QuorumType to be 'NodeAndFileShareMajority'? Has something changed in 2016 & "majority" seen above means 'NodeAndFileShareMajority' is it?

Is there any other way to verify QuorumType in Win Server 2016?

Thanks.


D


SQL Server Crash

$
0
0

Hello,

Our database unexpectedly shutdown, 


SQL Server version:Microsoft SQL Server 2017 (RTM) - 14.0.1000.169 (X64)   Aug 22 2017 17:04:49   Copyright (C) 2017 Microsoft Corporation  Enterprise Edition (64-bit) on Windows Server 2012 R2 Standard 6.3 <X64> (Build 9600: ) (Hypervisor) 

Event 1000, Application Error

----------
Faulting application name: sqlservr.exe, version:2017.140.1000.169, time stamp: 0x599d0bc0
Faulting module name: ntdll.dll, version:6.3.9600.19629, time stamp:0x5e2fdc0d
Exception code:0xc0000374

Faulting application path:

C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Binn\sqlservr.exe


Faulting module path:C:\Windows\SYSTEM32\ntdll.dll

MSSQL 2014 Version is 2014.120.4100.1 Patch Version: 2014.120.4232.0#. Why does the patch not resolve the MS16-136 security issue for SQL server 2014 SP1?

$
0
0

With scan on the machine where SQL server 2014 SP1 is installed I keep getting the same issue:

Microsoft Security Update for SQL Server (MS16-136)

I installed Security Update for SQL Server 2014 Service Pack 1 GDR (KB 3194720) which is recommended for the current SQL server 2014 version(12.1.4100.1). I applied both the 32 bit and 64 bit version but the issue is not resolved.

The vulnerability issue MS16-136 with the following message appearing for the patch: MSSQL 2014 Version is 2014.120.4100.1 Patch Version: 2014.120.4232.0#. 

Can someone please advise? Thank you.


 

TDE with Keyvault

$
0
0

I am reading this DOC. 

https://docs.microsoft.com/en-us/sql/relational-databases/security/encryption/setup-steps-for-extensible-key-management-using-the-azure-key-vault?view=sql-server-ver15&tabs=portal

Just not quite understand the following steps?

Why it's required to have another login to map for the credential to open the keyvault ?

And TDE_Login is a sql login,,,, can use Domain login ?

So this is the private key or public key ? and which steps in the docs really create a key in the key vault ?


Procedure to rotate TDE key on Azure Key vault

$
0
0

Hi all export. I would like to know the proper steps to rotate the TDE key which is on Azure KEY vault . 

the database is on Azure Vm, which installed SQL server . and also which is AAG, which the nodes are span at different Azure region . 

Recover readonly filegroup without restoring it from backup

$
0
0

Hi

I am not able to test the recovery of readonly filegroup from database file, without restoring it from backup, according to this MS article.

In two code examples bellow I have created a database with three custom filegroups. Two of them I set as readonly, then I made appropriate backups. After setting the database offline (option 1) or detaching it (option 2) I started to restore it. Restoring of the read/write filegroups worked, as well as restoring a readonly filegroup from the backup. However I was not able to recover the second readonly filegroup just from the database file, without using a backup. The error I got differed for option 1 and 2, please see SQL code bellow.

The server is SQL Server 2017 Enterprise Edition, the database was in simple recovery mode.

What do I do wrong?

Thank you, Martin

Option 1: restore after setting database offline

use master
go

xp_cmdshell 'mkdir T:\MSSQL\READONLY_FG_TEST_DB' ;
go

CREATE DATABASE [READONLY_FG_TEST_DB]
 CONTAINMENT = NONE
 ON  PRIMARY 
( NAME = N'READONLY_FG_TEST_DB__PRIMARY', FILENAME = N'T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB__PRIMARY.mdf' , SIZE = 5MB , MAXSIZE = UNLIMITED, FILEGROWTH = 512KB ), 
 FILEGROUP [FG_2018] 
( NAME = N'READONLY_FG_TEST_DB__DATA_2018', FILENAME = N'T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB__DATA_2018.ndf' , SIZE = 512KB , MAXSIZE = UNLIMITED, FILEGROWTH = 512KB ), 
 FILEGROUP [FG_2019] 
( NAME = N'READONLY_FG_TEST_DB__DATA_2019', FILENAME = N'T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB__DATA_2019.ndf' , SIZE = 512KB , MAXSIZE = UNLIMITED, FILEGROWTH = 512KB ), 
 FILEGROUP [FG_2020] 
( NAME = N'READONLY_FG_TEST_DB__DATA_2020', FILENAME = N'T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB__DATA_2020.ndf' , SIZE = 512KB , MAXSIZE = UNLIMITED, FILEGROWTH = 512KB )
 LOG ON 
( NAME = N'READONLY_FG_TEST_DB_log', FILENAME = N'T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB_log.ldf' , SIZE = 512KB , MAXSIZE = UNLIMITED , FILEGROWTH = 512KB)
GO


ALTER DATABASE [READONLY_FG_TEST_DB] SET RECOVERY SIMPLE
go

ALTER DATABASE [READONLY_FG_TEST_DB] MODIFY FILEGROUP [FG_2018] READONLY;  
GO  

ALTER DATABASE [READONLY_FG_TEST_DB] MODIFY FILEGROUP [FG_2019] READONLY;  
GO  

--backup of readonly filegroup FG_2018
BACKUP DATABASE [READONLY_FG_TEST_DB]
  FILEGROUP = 'FG_2018'
  TO DISK = N'T:\MSSQL\READONLY_FG_TEST_DB\backup__READONLY_FG_TEST_DB__FG_2018.bak'
go

--readonly filegroup FG_2019 intentionally without backup, target is recovery without restore from undamaged db file


--backup of read/write filegroups
BACKUP DATABASE [READONLY_FG_TEST_DB]
  READ_WRITE_FILEGROUPS
  TO DISK = N'T:\MSSQL\READONLY_FG_TEST_DB\backup__READONLY_FG_TEST_DB__RW.bak'
go



alter database READONLY_FG_TEST_DB
set restricted_user
with rollback immediate
go

alter database READONLY_FG_TEST_DB
set offline
go


--damage of files of read/write filegroups and one readonly filegroup FG_2018
xp_cmdshell 'del T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB__PRIMARY.mdf' ;
go
xp_cmdshell 'del T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB__DATA_2018.ndf' ;
go
xp_cmdshell 'del T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB__DATA_2020.ndf' ;
go
xp_cmdshell 'del T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB_log.ldf' ;
go


--partially restore of read/wrire filegroups
RESTORE DATABASE [READONLY_FG_TEST_DB]
   READ_WRITE_FILEGROUPS
   FROM DISK = N'T:\MSSQL\READONLY_FG_TEST_DB\backup__READONLY_FG_TEST_DB__RW.bak'
   WITH
      PARTIAL, RECOVERY
go



--restore of readonly filegroup FG_2018 from backup
RESTORE DATABASE [READONLY_FG_TEST_DB]
   FILEGROUP = 'FG_2018'
   FROM DISK = N'T:\MSSQL\READONLY_FG_TEST_DB\backup__READONLY_FG_TEST_DB__FG_2018.bak'
   WITH RECOVERY
go




--recovery of readonly filegroup from undamaged db file, without restore from backup, according to (https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/example-piecemeal-restore-of-only-some-filegroups-simple-recovery-model?view=sql-server-ver15)
RESTORE DATABASE [READONLY_FG_TEST_DB]
   FILEGROUP = 'FG_2019'
   WITH NORECOVERY
go
/*
Msg 5173, Level 16, State 1, Line 90
One or more files do not match the primary file of the database. If you are attempting to attach a database, retry the operation with the correct files.  If this is an existing database, the file may be corrupted and should be restored from a backup.
Msg 3013, Level 16, State 1, Line 90
RESTORE DATABASE is terminating abnormally.
*/

Option 2: restore after detaching database

Please see that in this this option the error states that the file should be in RECOVERY_PENDING state, however it is exactly the case.

use master
go

xp_cmdshell 'mkdir T:\MSSQL\READONLY_FG_TEST_DB' ;
go

CREATE DATABASE [READONLY_FG_TEST_DB]
 CONTAINMENT = NONE
 ON  PRIMARY 
( NAME = N'READONLY_FG_TEST_DB__PRIMARY', FILENAME = N'T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB__PRIMARY.mdf' , SIZE = 5MB , MAXSIZE = UNLIMITED, FILEGROWTH = 512KB ), 
 FILEGROUP [FG_2018] 
( NAME = N'READONLY_FG_TEST_DB__DATA_2018', FILENAME = N'T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB__DATA_2018.ndf' , SIZE = 512KB , MAXSIZE = UNLIMITED, FILEGROWTH = 512KB ), 
 FILEGROUP [FG_2019] 
( NAME = N'READONLY_FG_TEST_DB__DATA_2019', FILENAME = N'T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB__DATA_2019.ndf' , SIZE = 512KB , MAXSIZE = UNLIMITED, FILEGROWTH = 512KB ), 
 FILEGROUP [FG_2020] 
( NAME = N'READONLY_FG_TEST_DB__DATA_2020', FILENAME = N'T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB__DATA_2020.ndf' , SIZE = 512KB , MAXSIZE = UNLIMITED, FILEGROWTH = 512KB )
 LOG ON 
( NAME = N'READONLY_FG_TEST_DB_log', FILENAME = N'T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB_log.ldf' , SIZE = 512KB , MAXSIZE = UNLIMITED , FILEGROWTH = 512KB)
GO


ALTER DATABASE [READONLY_FG_TEST_DB] SET RECOVERY SIMPLE
go

ALTER DATABASE [READONLY_FG_TEST_DB] MODIFY FILEGROUP [FG_2018] READONLY;  
GO  

ALTER DATABASE [READONLY_FG_TEST_DB] MODIFY FILEGROUP [FG_2019] READONLY;  
GO  

--backup of readonly filegroup FG_2018
BACKUP DATABASE [READONLY_FG_TEST_DB]
  FILEGROUP = 'FG_2018'
  TO DISK = N'T:\MSSQL\READONLY_FG_TEST_DB\backup__READONLY_FG_TEST_DB__FG_2018.bak'
go

--readonly filegroup FG_2019 intentionally without backup, target is recovery without restore from undamaged db file


--backup of read/write filegroups
BACKUP DATABASE [READONLY_FG_TEST_DB]
  READ_WRITE_FILEGROUPS
  TO DISK = N'T:\MSSQL\READONLY_FG_TEST_DB\backup__READONLY_FG_TEST_DB__RW.bak'
go



alter database READONLY_FG_TEST_DB
set restricted_user
with rollback immediate
go

EXEC sp_detach_db 'READONLY_FG_TEST_DB', 'true';
go


--damage of files of read/write filegroups and one readonly filegroup FG_2018
xp_cmdshell 'del T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB__PRIMARY.mdf' ;
go
xp_cmdshell 'del T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB__DATA_2018.ndf' ;
go
xp_cmdshell 'del T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB__DATA_2020.ndf' ;
go
xp_cmdshell 'del T:\MSSQL\READONLY_FG_TEST_DB\READONLY_FG_TEST_DB_log.ldf' ;
go


--partially restore of read/wrire filegroups
RESTORE DATABASE [READONLY_FG_TEST_DB]
   READ_WRITE_FILEGROUPS
   FROM DISK = N'T:\MSSQL\READONLY_FG_TEST_DB\backup__READONLY_FG_TEST_DB__RW.bak'
   WITH
      PARTIAL, RECOVERY
go



--restore of readonly filegroup FG_2018 from backup
RESTORE DATABASE [READONLY_FG_TEST_DB]
   FILEGROUP = 'FG_2018'
   FROM DISK = N'T:\MSSQL\READONLY_FG_TEST_DB\backup__READONLY_FG_TEST_DB__FG_2018.bak'
   WITH RECOVERY
go




--recovery of readonly filegroup from undamaged db file, without restore from backup, according to (https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/example-piecemeal-restore-of-only-some-filegroups-simple-recovery-model?view=sql-server-ver15)
RESTORE DATABASE [READONLY_FG_TEST_DB]
   FILEGROUP = 'FG_2019'
   WITH NORECOVERY
go
/*
Msg 3149, Level 16, State 3, Line 89
The file or filegroup "FG_2019" is not in a valid state for the "Recover Data Only" option to be used. Only secondary files in the OFFLINE or RECOVERY_PENDING state can be processed.
Msg 3013, Level 16, State 1, Line 89
RESTORE DATABASE is terminating abnormally.
*/




select filegroup_name = substring(FG.name,1,10), FG.data_space_id, FG.is_read_only, file_name = substring(F.name,1,40), file_state_desc = substring(F.state_desc,1,20)
from READONLY_FG_TEST_DB.sys.filegroups FG join READONLY_FG_TEST_DB.sys.database_files F on F.data_space_id=FG.data_space_id 
go
/*
filegroup_name data_space_id is_read_only file_name                                file_state_desc
-------------- ------------- ------------ ---------------------------------------- --------------------
PRIMARY        1             0            READONLY_FG_TEST_DB__PRIMARY             ONLINE
FG_2018        2             1            READONLY_FG_TEST_DB__DATA_2018           ONLINE
FG_2019        3             1            READONLY_FG_TEST_DB__DATA_2019           RECOVERY_PENDING
FG_2020        4             0            READONLY_FG_TEST_DB__DATA_2020           ONLINE

*/

Safely stop full text catalog population?

$
0
0

SQL Server 2008 R2

We noticed that one of our full text catalogs was incorrectly set to "Do not track changes" with a "Last population date" set months ago. As soon as we set the Track changes setting to "Automatic", the Population status went to "Incrementally populating catalog"

The issue for us is that this is early morning of a work-day and it has rendered all file I/O access to result in Timeouts.

Is there a way to safely stop the population and resume it at a later time?

This catalog has a single table with 2 fields selected that are of data type: nvarchar(1000) and Image, which are BLOB's that represent the files our user's are now unable to access.


Recompile or DISABLE_PARAMETER_SNIFFING

$
0
0

If I would like to make the query to compile the plan for individual parameter, 

should I should recompile or DISABLE_PARAMETER_SNIFFING?

What's the different ?

Create table with ANSI_NULLS, ANSI_PADDING, CONCAT_NULL_YIELDS_NULL set off

$
0
0

What's the actual impact create table with deprecated set option ANSI_NULLS, ANSI_PADDING, CONCAT_NULL_YIELDS_NULL set off?

How to fix this ? Need to recreate the whole table ?

If the features is really discountiued , what's the affect on the current table with these option off ?

Sql Server CDC - Identifying affected tables from cdc.lsn_time_mapping

$
0
0
Hi, 
We have a SQl server DB enabled with CDC CHange data capture. 

I read about this function cdc.lsn_time_mapping ,

https://docs.microsoft.com/en-us/sql/relational-databases/system-tables/cdc-lsn-time-mapping-transact-sql?view=sql-server-ver15

and i run a query like 

Select * from dbname. cdc.lsn_time_mapping , return the start_lsn, tran_start_time, tran_end_time,tran id.

The documentation says, it returns one row for each transaction having rows in a change table. 

Is there any way to find out what tables a particular transaction has touched ?

I want to take a row from the output of cdc.lsn_time_mapping and use it to find out what tables have been impacted. 


Any suggestions please?

Performance of the database when I modify the MAXDOP parameter

$
0
0
Hi all

I don't understand the behavior of the database when I modify the MAXDOP parameter.

We have modified the MAXDOP parameter (from value 0 to value 4) to improve some processes with a quite good result, but when returning to the previous configuration (change from 4 to 0) the performance of the processes has been maintained without returning previous performance when the MAXDOP value was 0.

This has happened to us twice.

The first time was in a SQLServer instance in IaaS in Azure, we modified the value parameter 0 to 4 and the result was quite good, with a reduction of time of 50% in the processes that we studied.

The second time we did it in a SQL Azure Pool, we changed the value from 0 to 4, also the result was that the times improved a lot.

In both cases, when we reset MAXDOP to zero, the process times did not return to their initial and worse values.

We have cleared cache, execution plans, restored databases, and processes are still running at MAXDOP = 4 setup times.

How is this possible? Is there any explanation?

Regards

differences in the query plan xevent ?

$
0
0

what's the following difference ?

Fehler Initialisierung sqlcmd_Bibliothek

$
0
0

Der Aufruf von sp_send_dbmail mit einer Query funktioniert im SQL-Server Management Studio.

Der gleiche Aufruf in einem Schritt eines SQL-Agent-Auftrages bringt die Fehlermeldung

. Fehler bei der Initialisierung von sqlcmd-Bibliothek. Fehlernummer: -2147467259. [SQLSTATE 42000] (Fehler 22050)

Ein Aufruf dagegen ohne Query von sp_send_dbmail im SQL-Agent funktioniert.

Dem SQL-Agent sind Mailkonto und -profil zugewiesen.

Was fehlt

proactive performance metric list of points - threshold levels on each components

$
0
0

Hi 

I am looking  proactive performance   monitoring and thresholds to flag if something is going wrong with this.  I understand all SSMS -reports -> standared reports   ->  has bunch of reports . so none of them has say threshold level .

ex: page life  expectancy level  best level and flag in if going down 

      SQL use CPU and what is threshold level (before business call performance issue)

      TOP SQL  shows high CUPs ,but  system is responding good.  So justifying with evidence (basically threshold levels if can set)

 

If any one can advice would be  a load of thanks 

Ashwan


Inserts into a SQL database table that has a varbinary(max) column can be slow

$
0
0

We have the following stored procedure:

ALTER procedure [dbo].[spMergePPObjectBlobProperty]
(
    @values dbo.udtPPObjectBlobProperty readonly
)
as
begin

    begin try

        declare @updatetime datetime
        set @updatetime = GetUTCDate()

        merge tblPPObjectBlobProperty as t
        using (select * from @values) as s
        on t.InsertionId = s.InsertionId and t.PropertyMapNameId = s.PropertyMapNameId
        when matched then 
            update set UpdateTime = @updatetime, [Value] = s.BlobValue, UpdateId = s.UpdateId
        when not matched then
            insert (PropertyMapNameId, Value, UpdateId, UpdateTime, InsertionId) 
                values(s.PropertyMapNameId, s.BlobValue, s.UpdateId, @updatetime, s.InsertionId)
        option (loop join);

    end try
    begin catch

        declare @errormessage varchar(256)

        -- Get the error message
        select @errormessage = ERROR_MESSAGE()

        -- Raise an error and return
        raiserror('Error updating entries in the tblPPObjectBlobProperty Table. %s', 16, 1, @errormessage)

    end catch

end

Occasionally, this sp can take a few seconds to run with only several rows to insert. Other times it is extremely fast.

We have a number of these sps and this is the only one that appears to be slow sometimes and it is the only one that inserts into a table with a varbinary(max) column.

Can this stored procedure be optimised in any way?

sys.dm_io_virtual_file_stats (Transact-SQL)

start-cluster needed after stop-cluster?

$
0
0

For disk maintenance, I need to shut down both nodes of a SQL 2014 active/active cluster (DB + AS services). Not only maintenance mode for FCI but both VMs shutdown (infrastructure requirement).

  1. Shutdown applications
    2. Failover one node to the other (ends up with 2 instances on second node). Then can shutdown VM1(node that does not contain any cluster resource)
    3. On remaining VM shutdown cluster service (from the Cluster Manager) or PS Stop-Cluster
    4. Shutdown VM2


    5. restart first node (both instances restart on this node) 
    6. Restart second node. 
    7. Failover instance to second node

My question is if I stop-cluster before VM shutdown do I have to start-cluster once the VMs rebooted or the cluster will automatically start? I do not have environment to test.

the cluster resources contain only SQL + AS + drives into the resources as per below.

Thank you,

PS > Get-ClusterResource | select name, ownerGroup

Name                                                                     OwnerGroup

----                                                                    ----------

Analysis Services (INSTANCE_1)                                            SQL Server (INSTANCE_1)

Analysis Services (INSTANCE_2)                                            SQL Server (INSTANCE_2)

Backup VIP (INSTANCE_1)                                                   SQL Server (INSTANCE_1)

Backup VIP (INSTANCE_2)                                                   SQL Server (INSTANCE_2)

Cluster Disk 1                                                      Cluster Group

Cluster Disk 2                                                     SQL Server (INSTANCE_2)

Cluster Disk 3                                                      SQL Server (INSTANCE_1)

Cluster Disk 4                                                      Available Storage

Cluster IP Address                                                  Cluster Group

Cluster Name                                                        Cluster Group

SQL IP Address 1 (ContosoCluster_1)                                  SQL Server (INSTANCE_2)

SQL IP Address 1 (ContosoCluster_2)                                  SQL Server (INSTANCE_1)

SQL Network Name (ContosoCluster_1)                                  SQL Server (INSTANCE_2)

SQL Network Name (ContosoCluster_2)                                  SQL Server (INSTANCE_1)

SQL Server (INSTANCE_1)                                                   SQL Server (INSTANCE_1)

SQL Server (INSTANCE_2)                                                   SQL Server (INSTANCE_2)

SQL Server Agent (INSTANCE_1)                                             SQL Server (INSTANCE_1)

SQL Server Agent (INSTANCE_2)                                             SQL Server (INSTANCE_2)

Using sys.dm_db_index_physical_stats with Default Limited and index_level = 0

$
0
0

Fellow DBAs

I ran across an item in a refresher course about index internals.

It would be safe to say that we all have used sys.dm_db_index_physical_stats.  In my reading, it appears that when LIMITED is used as the parameter (which is the default) it does not go to the leaf level (index_level 0)

I see queries that are using Limited as the parameter and have index_level = 0 and alloc_unit_type_deesc = 'In_row_data'

Why is index_level = 0 needed in the WHERE if the dmv is not hitting the leaf level.

Thanks

MG.

There is insufficient system memory in resource pool 'internal' to run this query.

$
0
0

Dear colleague's,

I run SQL Server 2019 Developer edtion on my local Windows 10 Enterprise development machine.

Full version info:

Microsoft SQL Server 2019 (RTM-GDR) (KB4517790) - 15.0.2070.41 (X64)   Oct 28 2019 19:56:59   Copyright (C) 2019 Microsoft Corporation  Developer Edition (64-bit) on Windows 10 Enterprise 10.0 <X64> (Build 18363: ) 

I loaded a backup of one of our customers because he had a problem. The select query below gives the error "There is insufficient system memory in resource pool 'internal' to run this query." My SQL Server has 11 GB Memory assigned to it. If I recompile the function "Get_LookupDescription" without changing a letter of code, the query is ready in a jiffy and returns no rows at all. Even when I try to only Display the Estimated Execution plan, I get the insufficient memory error. I thought that the query itself wasn't executed if you only wanted to know the estimated execution plan. Does anybody have any idea what might be going on? The customer can work because I recompiled the function on his system. Luckily, I had a backup of the database that reproduces the problem every time I load it.

CREATE TABLE [dbo].[FieldValues]
(
  [TableId]       int NOT NULL,
  [PrimKey]       nvarchar(255) NOT NULL,
  [FieldDefCode]  nchar(15) NOT NULL,
  [LookupValue]   nvarchar(25) NULL,
  CONSTRAINT [PK_FieldValues] PRIMARY KEY CLUSTERED ([FieldDefCode], [TableId], [PrimKey])
);
GO

CREATE TABLE [dbo].[LookupFieldDefinitions]
(
  [TableId]        int NOT NULL,
  [FieldDefCode]   nchar(15) NOT NULL,
  [RefTableId]     int NOT NULL,
  [DefaultLookup]  nvarchar(25) NULL,
  CONSTRAINT [PK_LookupFieldDefinitions] PRIMARY KEY CLUSTERED  ([TableId], [FieldDefCode])
);
GO

CREATE TABLE [dbo].[Parts]
(
  [PartCode]     nchar(15) NOT NULL,
  [Description]  nvarchar(30) NOT NULL,
  CONSTRAINT [PK_Parts] PRIMARY KEY CLUSTERED ([PartCode])
);
GO

CREATE TABLE [dbo].[Employees]
(
  [EmpId]  nchar(8) NOT NULL,
  [Name]   nvarchar(30) NOT NULL,
  CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED ([EmpId])
);
GO

CREATE FUNCTION dbo.Get_LookupDescription
  ( @TableId  int           = NULL
  , @PrimKey  nvarchar(255) = NULL
  )
RETURNS nvarchar(255)
AS   
BEGIN  
  DECLARE @LookupDesc  nvarchar(255) = N'';

  IF @TableId = 12
    SELECT @LookupDesc = [Description] FROM dbo.Parts WHERE PartCode = @PrimKey
  ELSE IF @TableId = 13
    SELECT @LookupDesc = [Name] FROM dbo.Employees WHERE EmpId = @PrimKey
  ;

  RETURN @LookupDesc;  
END;
GO

DECLARE
  @TableId  int           = 12
, @PrimKey  nvarchar(255) = N'006131-0043'
BEGIN
  SELECT dbo.Get_LookupDescription(DEF.RefTableId, ISNULL(VAL.LookupValue, DEF.DefaultLookup)) AS LookupDescValue
  FROM LookupFieldDefinitions AS DEF WITH (READUNCOMMITTED)
  LEFT OUTER JOIN dbo.FieldValues AS VAL
    ON VAL.FieldDefCode = DEF.FieldDefCode
    AND VAL.TableId = DEF.TableId
    AND VAL.PrimKey = @PrimKey
  WHERE DEF.TableId = @TableId
END;
GO


Viewing all 15930 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>