text
stringlengths 209
10.7k
|
---|
<s>[INST]Unable to shrink logfile for datbase with memory optimized filgroup
I have a database with Recovery Model: Simple
The logfile is quite large.
- running DBCC SHRINKDATABASE(dbname, 0) shrinks the transaction log just fine.
Now, for that same database (restore from backup, pre-shrink), if I add a memory optimized filegroup, and some memory-optimized user defined table types, and then try and run the same shrink operation, I receive the following message:
> Cannot shrink log file 2 (dbname_log) because the logical log file located at the end of the file is in use.
dbcc loginfo shows Status=2 for the first entry, and the last 2 entries. The entries in the middle are Status=0
sys.databases.log_reuse_wait_desc for this database is NOTHING
DBCC SHRINKFILE has the same issue. I have tested, and experienced the same behavior on SQL 2017 CU28, and SQL 2019 CU10
Question:
- is this some limitation of having a memory-optimized filegroup present in the database?
- Is there a "graceful" way to shrink this logfile without having to take the database offline, and building a new log?
[/INST]To shrink a log file, the part at the end has to be empty, so you may have to cause it to wrap around. Often a couple of CHECKPOINT and log backups (if you are on FULL recovery) is sufficient.
To my knowing, there is nothing particular with memory-optimized filegroups.</s>
|
<s>[INST]Does Transact-SQL have a funtion that can determine whether daylight savings was in effect on a given datetime?
Hi,
I am using SQL Server Express (64-bit) version 14.0.1000.169. I have a database in which I have a table with a 'datetime' field. The PC on which this database resides is in the Eastern Time Zone (US and Canada, UTC-05:00). Our times here are adjusted for Daylight Savings Time - we move our time one hour forward in the spring and then one hour back in the fall.
I am querying this database from an application (built using a 3rd party Industrial Automation Process Visualization and Historian Software package) in which one of the features cannot handle date/time information in the same format that the SQL Server 'datetime' Data Type does. This particular feature requires that date/time information must be set with a value equaling the number of seconds since Jan 1, 1970. This application has a function called ITXCreateDateTime that allows me to determine the number of seconds since Jan 1, 1970 as follows:
SecondsSinceJan1_1970 = ITXCreateDateTime(year,month,day,hour,minute,second);
The value returned by this function reflects GMT time, so for me to use it, I have to add an Offset reflecting the difference between local time and GMT time. When daylight savings time is in effect, this offset is 18,000 (5 hours difference). When daylight savings time is not in effect, this offset is 14,400 (4 hours difference). What I am stuck on is that this application does not seem to have a function that allows me to determine whether Day Light Savings time was in effect on a past date. (It does have a function that allows me to determine whether Daylight Savings time is in effect on the current system date, but this does not help me for what I am trying to accomplish).
As I feel like I might not be able to accomplish what I want entirely within the application itself, I am wondering if Transact SQL has a feature that would allow me to determine whether Daylight Savings Time was in effect on a given date. If this is supported, and can include this as a Boolean in my query results, and use this in my application to determine the required offset.
Any suggestions will be greatly appreciated.
Thanks and best regards,
Paul[/INST]for solving the problem in the wrong direction. My lame excuse is that it is a lot more common that people ask about how to convert a Unix timestamp to the SQL Server data types and the other way round.
Here is a new function:
CREATE OR ALTER FUNCTION LocalTimeToUnixTime(@local datetime, @timezone varchar(50)) RETURNS bigint AS
BEGIN
DECLARE @do datetimeoffset(3) = @local AT TIME ZONE @timezone
SELECT @do = switchoffset(@do, '+00:00')
RETURN datediff_big(second, '19700101', convert(datetime2(3), @do))
END
go
SELECT dbo.LocalTimeToUnixTime('2021-02-12 04:10:00.000', 'Central European Standard Time')
This time I made the time zone a parameter so I could test in my local time.
As for the data types, SQL Server has both `datetime` and `datetime2` due to legacy. `datetime` has a range from 1754-01-01 to 9999-12-31, and a resolution of 3.33 ms. A `datetime` value takes up eight bytes. `datetime2` has a range from 0001-01-01 (but always according to the Gregorian calendar) to 9999-12-31, and you can select from a resolution of full seconds (`datetime2(0)`) down to 100 ns (`datetime2(7)`.) Stupidly, if you say `datetime2` this is the same as `datetime2(7)`, but you very rarely have need for a resolution of more than 1 ms, since this is what you get from the function sysdatetime(). (getdate() returns `datetime`, so here you only get 3.33 ms.) `datetime(0)` to `datetime(2)` take up six bytes, whereas `datetime2(3)` and `datetime2(4)` take up four bytes.
One advantage with `datetime2` is that date strings on the format YYYY-MM-DD always work. This is not the case with datetime.</s>
|
<s>[INST]Comparison between two sets of servers
Hello,
I need to compare to sets of servers and try to find out a SQL statement to do so:
Server Name, Operating System, Drive letter, Size, Free Space, % Free, Ram Size, Page Size, Virtual Memory
and if possible to display the results as:
## on one line...
ServerA-Operating System-Drive-Size-Free Space-Ram Size-Page Size-Virtual Memory / ServerB-Operating System-Drive-Size-Free Space-Ram Size-Page Size-Virtual Memory
## Order by Server Name starting by the 6th character
or on two lines
---------------------------------------------------------------------------------------------------------------------------ServerA-Operating System-Drive-Size-Free Space-Ram Size-Page Size-Virtual Memory
ServerB-Operating System-Drive-Size-Free Space-Ram Size-Page Size-Virtual Memory
## with an Order by the name character starting in position 6?
Thanks,
Dom
[/INST]it is not possible to achieve your requirement by SQL server query. We can use SQL query to get the information about SQL server. Such as the memory that currently be allocated to SQL server, etc.
Your issue is more related to windows server, suggest you add **windows-server** tag, people there will give you a better help.</s>
|
<s>[INST]Msg 195, Level 15, State 10, Procedure SP_Time_Attendance_Register, Line 87 'CONCAT' is not a recognized built-in function name.
I am using concat in sql server 2008 ,but it is giving on below line,
, Line 87 'CONCAT' is not a recognized built-in function name.
so how to use concat or other solution for this
THEN CONCAT(convert(varchar(30),CAST(TimeIN as Time ),100),CHAR(10),convert(varchar(30),CAST(TimeOut as Time),100))
ELSE CONCAT(convert(varchar(30),CAST(TimeIN as TIme),100),CHAR(10),convert(varchar(30),CAST(TimeOut AS Time),100),CHAR(10),[STATUS]) END RESULT,
[/INST]concat function was added to sql server 2012 or above.
You are way behind now.
Without concat:
THEN convert(varchar(30),CAST(TimeIN as Time ),100)+CHAR(10)+convert(varchar(30),CAST(TimeOut as Time),100)
ELSE convert(varchar(30),CAST(TimeIN as TIme),100)+CHAR(10)+convert(varchar(30),CAST(TimeOut AS Time),100)+CHAR(10)+[STATUS]</s>
|
<s>[INST]Replace leading 44 with 0 for phone numbers
Hi there,
I would like to replace leading 44 or 44+ with zero for phone numbers. Can you please suggest me how to do this?
create table phonenumber (ObjectId int , Number nvarchar(20))
insert into phonenumber
values (1001,'447875288997'),
(1002,'+4412674498589'),
(1003,'4408690446873'),
(1004,'07875288996'),
(1005,'086678764889')
[/INST]Please try the following solution.
It will work starting from SQL Server 2017 onwards.
**SQL**
-- DDL and sample data population, start
DECLARE @tbl TABLE (ObjectId int PRIMARY KEY, Number nvarchar(20));
INSERT INTO @tbl (ObjectId, Number) VALUES
(1001,'447875288997'),
(1002,'+4412674498589'),
(1003,'4408690446873'),
(1004,'07875288996'),
(1005,'086678764889'),
(1006,'086678744889');
-- DDL and sample data population, end
DECLARE @countryCode VARCHAR(3) = '44';
SELECT *
, Result = TRIM('+' FROM IIF(pos IN (1,2),STUFF(Number, pos, LEN(@countryCode), 0),Number))
FROM @tbl
CROSS APPLY (SELECT CHARINDEX(@countryCode, Number)) AS t(pos);
**Output**
| ObjectId | Number | pos | Result |
| 1001 | 447875288997 | 1 | 07875288997 |
| 1002 | +4412674498589 | 2 | 012674498589 |
| 1003 | 4408690446873 | 1 | 008690446873 |
| 1004 | 07875288996 | 0 | 07875288996 |
| 1005 | 086678764889 | 0 | 086678764889 |
| 1006 | 086678744889 | 8 | 086678744889 |</s>
|
<s>[INST]Transaction log full error 9002 on AG
Hi All,
I am looking for some inputs on how to avoid or prevent this particular scenario which happened yesterday. there was downtime of 4 hours.
Below is the scenario
We have a Multi-subnet Alwayon AG configured with 10 databases. AG has 3 nodes. All are azure VMs.
2 nodes in one region and 1 node is in a different region.We are using SQL Server 2017 Enterprise edition CU23 version.
Issue description:
On Primary replica one of the user db's transaction log file of a database which is part of AG got full (9002 log full error).
The mdf is 20gb and log file has grown ~ 400GB. The data and log files are located in separate drives. every hour we take log backups.
The drive capacity of log file is 500GB.
So, to minimize the downtime , we tried adding space on secondary synchronous replica and wanted to fail over.
After adding space and when we rebooted the server didn't come online. it took like 20 mins to come up.
Secondly, the cluster service was not coming online due to which , we aren't able to do a fail over to the secondary node.
After systems escalation team was involved , they finally was able to bring the cluster service online which took another 30-45 mins to analyze the logs.
We eventually failoved over to the secondary and made it primary. We followed same steps to add it on remaining nodes.
We are suspecting all this could have happened due to a long running open txn and it is waiting for AVAILABILITY_REPLICA log_reuse_wait_desc. We asked application team if they have run an transaction, they said they haven't.
observations:
1. We have disk space monitoring in place, but the incident was with system's team and they haven't notified.
2. We got an sql server alert only for log full 9002 error.
I am looking for inputs on how can avoid some disk space issues in future.
My thoughts
- \> I am thinking about configuring another sql alert to send email when the log file is reached 50% .
- \> restrict auto growth of the log file
Please share more thoughts on this on how to minimize of handle such situations more efficiently.
Also, is there a way we can tell/send a list of spids/txns which caused the log file to get full?
Thank you.
Sam
[/INST]1. We have disk space monitoring in place, but the incident was with system's team and they haven't notified.
So there was an alert, and the team who got the alert, did not react? Looks like you have a workplace problem, rather than a technical problem.
> I am thinking about configuring another sql alert to send email when the log file is reached 50% .
Maybe.
> restrict auto growth of the log file
So that you get error 9002 earlier and less margin if there is an incident?
How about ask yourself whether you should have an AG. The purpose of an AG is to get high availability, but now you got a four-hour outage because you had an AG?
Maybe you should have a FCI instead? Maybe less sophisticated, but I think also easier to manage.</s>
|
<s>[INST]How to tell what sql stmts are taking up more MEMORY in SQL Server
Hi,
Recently, we got high memory incidents from monitoring tool. I have lowered the max server memory for time being.
Using SQL Server 2016 Enterprise Edition.
From task mgr I see sqlservr.exe is the one taking up 85% memory (i.e. workingset value).
Now I want to know withing sql server , what are the sql queries are taking up more memory.
I used sp_whoisactive but I am seeing "used_memory" column values as 2,3,9, 79,243 , 4,221. I am not sure what is the value indicate, is it number of 8K pages?
Is there are proper way to tell which statements taking most memory in MB/GB and I wanted to store them in a table. This information will be share to developers.
Thank You![/INST]This is a useful query that I got from Dmitri Korotkevich's book SQL Server Advanced Troubleshooting:
SELECT TOP 15
[type] AS [Memory Clerk]
,CONVERT(DECIMAL(16,3),SUM(pages_kb) / 1024.0) AS [Memory Usage(MB)]
FROM sys.dm_os_memory_clerks WITH (NOLOCK)
GROUP BY [type]
ORDER BY sum(pages_kb) DESC;
Normally you will see MEMORYCLERK_SQLBUFFERPOOL to be lot bigger than anything else. Exactly how much bigger depends on how much RAM you have available. But let me put it this way: if any other clerk has more than 10 GB of RAM, I find that noticeable.</s>
|
<s>[INST]Error inserting in Microsoft Access 2002-2003 "long Text" field SQL Server 2019 linked Server Microsoft Access Database Engine 2010 x64
I am attempting to migrate a number of stored procedures, which insert to Microsoft Access 2002-2003 format database files, as linked servers.
The process is currently working fine on the following configuration
Windows Server 2008 R2 Standard
SQL Server 2014
Microsoft Access Database Engine 2010 x64 - v14.0.7015.1000
The updated configuration is as follows
Windows Server 2019 Datacenter
SQL Server 2019
Microsoft Access Database Engine 2010 x64 - v14.0.7015.1000
The Microsoft.ACE.OLEDB.12.0 has registered fine on the newer server configuration, and is available as a linked server "provider"
The SP inserts to a number of tables, with varying data types, and all are successful, with the exception of fields where the SQL Server field is of type nvarchar and the Access mdb field is of type "Long Text", where I get the error.
Msg 7344, Level 16, State 1, Line 182
The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "[Access mdb Linked Server Name]" could not INSERT INTO table "[Access mdb as Linked Server]...[Table Name]" because of column "[Column Name]". The column had a bad status.
The Long text fields in the Access mdb are reported/displayed as varchar data type, in the linked server configuration.
I have tried writing simple, short, strings to the field, CASTing as varchar data type, but still get the same error.
I've done lots of googling, but can find no examples of others experiencing similar issues.
I suspect it is a compatibility issue, between the SQL server version and access database engine but, again, have been unable to find any useful resource.
Has anyone experienced a similar issue, and found a resolution?
Or if you can direct me to a suitable resource where I can find more info.[/INST]This sounds like an Access problem to me.
To wit, SQL Server does not really know that it is talking to Access. It talks to an OLE DB provider for the data source. Exactly how it does that depends on what capabilities the OLE DB provider exposes.
As you seem to have the same OLE DB provider in both setups, one like to think that it should work in both cases. But it could be that SQL Server talks to the OLE DB provider in a different way which provokes this error. But to troubleshoot it, you would need to be on the Access side of this.
(I'm an SQL Server guy, with no experience of Access.)</s>
|
<s>[INST]Can I drop or disable the default NT Service Accounts from SSMS Logins?
The following accounts are automatically created upon SQL Server installation:
- NT SERVICE\SQLWriter
- NT SERVICE\Winmgmt
- NT SERVICE\MSSQLSERVER
- NT SERVICE\SQLSERVERAGENT
If I am using a seperate domain account to use as SQL Service and SQL Agent login, is it safe to disable/ delete these default accounts?
[/INST]These accounts are created by default with SQL server installation. I consider them harmless. I suggest you do not delete them.
The SQL Writer service uses the NT Service\SQLWriter login to connect to SQL Server. Using the NT Service\SQLWriter login allows the SQL Writer process to run at a lower privilege level in an account designated as no login, which limits vulnerability. If the SQL Writer service is disabled, then any utility which in relies on VSS snapshots, such as System Center Data Protection Manager, as well as some other 3rd-party products, would be broken, or worse, at risk of taking backups of databases which were not consistent.
Windows Management Instrumentation (WMI) must be able to connect to the Database Engine. To support this, the per-service SID of the Windows WMI provider (NT SERVICE\winmgmt) is provisioned in the Database Engine.
For NT Service\MSSQLSERVER and NT Service\SQLSERVERAGENT, if they are no longer the service account for SQL server service and agent service, you should be able to disable them , provided that they don't own any objects or the like.</s>
|
<s>[INST]SQL Logs - Multiple successful logins per second
SQL 2017
We're seeing multiple successful logins from the service account that's running SQL, to the tune of up to 42 entries per second. They're coming from the server itself, not a client. Why so many, and is there a way to figure out what's causing them so we can get rid of them? Besides turning off logging of successful logins of course.
Message
Login succeeded for user 'MyServiceAcct'. Connection made using Integrated authentication. [CLIENT: <local machine>]
Thanks in advance[/INST]Could be a loopback connection through the CLR. Could also be a different program that runs under the same account.
I would try run a trace/X-event session to see what commands these process run to see if that sheds some light on the situation. In the trace itself, the ClientProcessID column is quite much of interest.</s>
|
<s>[INST]Patching SQL Server 2016 SP2 13.0.5865.1 to SP3 GDR
Hi, can a SQL server 2016 that is currently on SP2 CU15 Security Update 13.0.5865.1 , be patched to the latest SP3 GDR in the following order, to avail the extended support until July 2026?
1. Upgrade to SP3 first, 13.0.6300.2 and then upgrade to SP3 GDR Security Update KB5014355, 13.0.6419.1?
2. Or Is it recommended to upgrade to SP3 13.0.6300.2 and not do the latest GDR?
SQL Server installations were intentionally installed previously with CU updates, and CU security update package. SQL 2016 SP2 support will end in Oct 2022, and there are no CU in SP3.
Thanks, Kellwyn
[/INST]\> can a SQL server 2016 that is currently on SP2 CU15 Security Update 13.0.5865.1 , be patched to the latest SP3 GDR in the following order
Yes, you can do that.
> \> Upgrade to SP3 first, 13.0.6300.2 and then upgrade to SP3 GDR Security Update KB5014355, 13.0.6419.1?
Yes, you are right.
> \> Or Is it recommended to upgrade to SP3 13.0.6300.2 and not do the latest GDR?
No, suggest you applying the latest GDR for your SQL server instance. But you need to know below notes.
What are the GDR and CU update designations and how do they differ?
The General Distribution Release (GDR) and Cumulative Update (CU) designations correspond to the two different servicing options in place for SQL Server baseline releases. A baseline can be either an RTM release or a Service Pack release.
o GDR updates – cumulatively only contain security updates for the given baseline.
• CU updates – cumulatively contain all functional fixes and security updates for the given baseline.
Note: You are allowed to make a change from GDR updates to CU updates ONE TIME. Once a SQL Server CU update is applied to a SQL Server installation, there is NO way to go back to the GDR update path.</s>
|
<s>[INST]using SSMS query designer with master
I'm trying to write a query for master using SSMS query designer, the login server role is sysadmin, I have tried to map to all database roles for master however the add table
window is always empty, you can´t see any table nor any view, please any idea.[/INST]I used Profiler to see what queries the Query Designer submits. The pane for tables queries sys.tabels, which only returns user tables, not system tables. The pane for views queries sys.all_views which does return system views. But there is a column IsSystemObject in the result set, and I guess the UI filters out rows where this column is 1. There is not much you can do about it.
You may not like what I will say here, but as I see it, the Query Designer is an aide for very inexperienced SQL persons. But it is something you should grow out of. When your were a kid, I guess your first bicycle was a three-wheeler or and extra supporting wheels to help you with the balance. But as you grew older and learnt to master bicycling, you stopped using them and you progressed to a normal two-wheel bicycle. And the same thing with the Query Designer. While it can be helpful in the beginning, it becomes an obstacle, because there are SQL constructs the Query Designer does not support.
Why SSMS filters out system objects, I don't know. But maybe the reasoning is that if you have become that advanced that you query system objects, you no longer need the Query Designer.</s>
|
<s>[INST]Power Pivot - Impossible to change connection from SQLOLEDB to MSOLEDBSQL - Wizard wont keep the change
Hi
I have a PowerPivot model that uses SQLOLEDB and was working fine connecting to SQL Server 2012 (on Windows server 2012)
We upgraded our serveur from SQL2012 to SQL2019 on an Azure VM. (ForceEncryption is off (=0) on the server)
Now provider SQLOLEDB does not connect to new server IN POWERPIVOT Existing Connection Wizard
Note : all machines have Microsoft OLE DB Driver for SQL Server v18.5 (or 18.6.4) (Tried 18.3 as well)
So I went to Excel, PowerPivot, Manage, Existing Connection, Edit the connection
Change for new server of course
Clicked (Advanced)
Changed provider from SQLOLEDB to MSOLEDBSQL
set Use Encryption for data=False (Not "Optional" which is for driver 19 that nobody wants. I did tried v19 - this absolutly never connected even with Encryption for data=Optional)
set Trust Server certificate=True (but anyway the server does not have any)
Click (Test connection). It connects successfully.
Then click (OK) , close Wizard.
There is another (Test Connection) in this window. It fails.
I go back to (Advanced) and the Provider is back to SQLOLEDB. The change to MSOLEDBSQL was not saved.
I copied the generated connection string and pasted it in one of my other c# program and it connects
The connection string is correct. PowerPivot wizard does not keep the selected provider after clicking (OK)
When the connection string has Provider=SQLOLEDB I get an SSL error (even when Use Encryption for data=False)
When the connection string has Provider=MSOLEDBSQL it connects. Unfortunatly the connection string show MSOLEDBSQL only while in the Advanced windows.
It revert back to SQLOLEDB has soon as the Advanced window is closed.
Use Encryption for data=False in all cases
I created a new Workbook, started PowerPivot, Add connection from database, Sql Server .... same problem once provider is changed and return to edit it is not changed.
So instead in this new workbook, I select **from other source,** , Selected Other(OLEDB/ODBC) (IF I select Sql Server it wont work) pasted the connect string that was generated from previous wizard ... IT WORKS.
If I dont paste the connectstring and use the Wizard, in the provider list there are:
Microsoft OLE DB Driver for SQL Server (This one works. It is proabably v18)
Microsoft OLE DB Provider for SQL Server (This one does not work. This is probably a PRE v18)
So for a brand new workbook and selecting OtherSource, Other (OLEDB/ODBC) it works
The problem is that I have several Excel file with PowerPivot models. I cannot create new ones
I need to be able to change the connection in current models
I have several Terminal Servers all on Azure now.
Some recent Azure VMs (showing Windows 10 and Excel 2022 and other in WIndows Server 2016 and Excel 2008)
My Azure VMS are:
Windows 10 and Excel 2022 build 14931. Works
Windows Server 2019 and Excel 2108. Works
All others VMs are running WIndows Server 2016 And Excel 2008 - NONE works (PowerPivot unable to connect after clicking (OK) on the Advanced window. Works only with the (Test connection) button.
Using EXACT SAME Workbook file.
I cannot simply upgrade the OS
I cannot simply upgrade Excel
Is it an Excel version issue OS version Issue ?
Not a TLS issue since the (Test connection) button works, and the connection string using Provider=MSOLEDBSQL with Encryption for data=False does work in a c# program of mine on all machines.
help please
[/INST]I'm not sure why you tagged this with sql-server-general only, since this apparently an Excel problem.
But maybe the issue is that this antique version of Excel does not know about MSOLEDBSQL, and therefore drops it on the floor.
> Microsoft OLE DB Driver for SQL Server (This one works. It is proabably v18)
Yes, this is MSOLEDBSQL.
> Microsoft OLE DB Provider for SQL Server (This one does not work. This is probably a PRE v18)
Yes, this is SQLOLEDB. In between these, there were also SQLNCLI, SQLNCLI10 and SQLNCLI11, but you would need to install them to be able to use them. (SQLOLEDB comes with the OS.)</s>
|
<s>[INST]Ho to have more than 10gb database in sql server?
Hi all,
I have sql server created on my PC, but on this server is a 10GB limit of database. I need more ... do you know how to get more?
Thank you[/INST]If the database is only for non-production use (development and testing), you can use Developer Edition. Developer Edition does not have the database size limitations of Express Edition.</s>
|
<s>[INST]How can I generate strictly increasing numbers
Dear colleagues,
I use SQL Server 2019, Standard Edition.
Our table with journal entries has a strictly increasing PK field. Nothing weird there.
With strictly increasing I mean that even when a rollback happens, the next insert will not cause a gap.
We have a table with one record containing the last used number. Every transaction posting a journal entry does the following.
- Start a transaction
- Lock the table with the last used number (always the first action to prevent deadlocks on this table)
- Get the number, increment it and post the new number
- Do the rest
- Commit or Rollback (when a rollback is issued, also the increment is rolled back)
This works, but when a long running transaction creates journal entries, this causes awful performance degradation (for obvious reasons). I cannot use an identity column because the journal entries are stored in several tables sharing the same PK. I want to use a sequence to prevent the problems we have now. However, even if the sequence doesn't cache values, we still can have gaps in the numbering in case of a rollback. The accountants do not like this.
My question:
Is there a way to add a new column that I can populate with a strictly increasing number that is assigned after transactions are committed? As far as I know, there is no way I can receive a notification when a transaction is committed. I do not find it a problem if the new column doesn't have the same order as the PK. This might happen in the following scenario.
- Last used PK = x, last used stricly increasing number = y
- Transaction A starts and gets PK = x+1
- Transaction B starts and gets PK = x+2
- Transaction C starts and gets PK = x+3
- Transaction C commits and gets PK = x+3, Increasing number = y+1
- Transaction B rolls back
- Transaction A commits and gets PK = x+1, Increasing number = y+2
(gap between x+1 and x+3, increasing number in different order)
[/INST]You are apparently talking about wanting a sequence based on the order transactions are committed. There are several reasons why identity/sequences skip number, mostly for performance and blocking with large numbers of transactions.
There is nothing built-in which would run after commit. The simplest answer to your question is to create a trigger AFTER INSERT which uses a sequence or max(seq) and inserts the value. However, depending on where that runs, it might also skip numbers and is going to be prone to blocking if you have a large number of transactions.
You are likely better off creating a job to update the number. But you still don't know the order of the items committed.
Without knowing more about what exactly you are trying to do, it is hard to give an exact answer.</s>
|
<s>[INST]How to trap error from SQL AGENT JOB in SSMS
I created an AGENT JOB that executes about 12 steps, each one with its own SQL Script. These scripts simply update data in our DBs.
In the scripts, I included try/catch and begin tran/end tran in this order:
BEGIN TRY
BEGIN TRANSACTION
SQL here......
COMMIT TRANSACTION
...Write to Log...
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
...Write to Error Log...
END CATCH
However, when I get an error message, it comes from the Job system,
saying "The last step to run was step 9" for example. That implies
it couldn't run step 10.
Is there a way to know exactly *why* it failed to run step 10?
I don't think it's in the SQL script because it never writes to my error log in
the begin/end catch block.
Any thoughts?[/INST]The SQL Server Agent maintains its own error log, separate from the SQL Server error log. the default name of the SQL Server Agent error log is SQLAGENTOUT.
The system maintains 10 SQL Server Agent error log files. The paths where the agent error log files are stored are: C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Log, and the file names are: SQLAgent.out, SQLAgent.n (n=1, 2, 3, 4, 5, 6, 7, 8, 9), where SQLAgent.out records the current messages of the agent.
Users can use the Log Viewer to view the memory of the logs. Users can open Management to view SQL Server Logs, select "Current-xxx" to view the current log file and double click to open the log using the log viewer.</s>
|
<s>[INST]How to use count over partition with cte instead of using having ?
I work on sql server 2017 i have issue i can't use count over partition instead of using having distinct
main statment i use
SELECT P.PartsFamilyID, P.PackageID, R.RoHSStatus
FROM Parts.ManufacturingData M WITH(NOLOCK)
INNER JOIN Parts.Nop_Part P WITH(NOLOCK) ON P.PartID = M.PartID
INNER JOIN Parts.ROHS R WITH(NOLOCK) ON R.ZPartID = P.PartID
where packageId is not null
GROUP BY P.PartsFamilyID, P.PackageID, R.RoHSStatus
HAVING COUNT(DISTINCT M.LeadFinishPlatingID) > 1 OR COUNT(DISTINCT M.BaseMaterialID) > 1
i need exactly rewrite statment above using count over partition with cte
with ctemanufacture as
(
)
select * into #test from rn1 > 1 or rn2>1
so please
How can i do that please ?
[/INST]using count over partition with cte
When you use `Count( DISTINCT LeadFinishPlatingID) OVER( PARTITION BY ...... )` ,there will be an error: 'Use of DISTINCT is not allowed with the OVER clause.'
You can have a try on another solution, using DENSE_RANK. Plesase check this:
;WITH ctemanufacture AS
(
SELECT P.PartsFamilyID, P.PackageID, R.RoHSStatus,
DENSE_RANK()OVER(PARTITION BY P.PartsFamilyID, P.PackageID, R.RoHSStatus ORDER BY M.LeadFinishPlatingID)
+ DENSE_RANK()OVER(PARTITION BY P.PartsFamilyID, P.PackageID, R.RoHSStatus ORDER BY M.LeadFinishPlatingID DESC) - 1 AS rn1,
DENSE_RANK()OVER(PARTITION BY P.PartsFamilyID, P.PackageID, R.RoHSStatus ORDER BY M.BaseMaterialID)
+ DENSE_RANK()OVER(PARTITION BY P.PartsFamilyID, P.PackageID, R.RoHSStatus ORDER BY M.BaseMaterialID DESC) - 1 AS rn2
FROM Parts.ManufacturingData M
INNER JOIN Parts.Nop_Part P ON P.PartID = M.PartID
INNER JOIN Parts.ROHS R ON R.ZPartID = P.PartID
WHERE packageId is not null
)
SELECT PartsFamilyID, PackageID, RoHSStatus --INTO #test
FROM ctemanufacture
WHERE rn1 > 1 or rn2>1</s>
|
<s>[INST]Can insufficent memory cause allocation & extent errors?
SQL Server 2014 SP3 GDR
Can insufficient memory cause allocation & extent errors?
Let's say you have 168 databases on this instance. One of them is 2.4TB in size and four others 1TB +
Just barely 1TB of memory.
Hybrid environment, lots of loading, bulk inserts while many reads are going on. Searches come from the application which are most parallel and bad in general. Developers throwing their own monsters into the mix.
The disk array is about 5 to 10 years old. DBA doesn't get to look and evaluate the VMS or host.
Outside consulting firm came in for an audit and deemed the servers configured correctly except under resourced. Recommended splitting out some of those VLDB's and adding 1TB of memory. They also recommended changing maxdop from 8 to 4. However since then we have had memory dumps. I agree that we should split out these VLDBS, increase memory and update firmware especially on disk.
A dbcc checkdb cleared the allocation and extent errors.
I am telling my manager that we need to increase memory so we can handle the size of these databases until we get resources to split them off. However he does not believe me that memory is the issue here.
Can a guru here help me make my case? Thank you for helping your fellow DBA's. [/INST]You don't get allocation errors and extent errors just because the system is overloaded. You get it because some piece of your hardware is faulty. Hardware here includes the I/O subsystem, and there can be issues with drivers etc.
It could however be that the load takes more strain on the machinery, that you are more likely to provoke these errors to happen.
Getting inconsistency warnings is a big warning sign. This time DBCC might have been able to fix them. Next time, if may not be fixable without data loss - or restoring a backup.
As for the patch level, it certainly does not hurt to be on CU4. Note that to get there, you will first need to uninstall the current GDR and then apply CU4. And the apply the corresponding GDR for CU4.</s>
|
<s>[INST]SQL connection open failed when using MS OLE DB Driver 19 for SQL Server
Hi Team,
Uninstalled the older version of "Microsoft® OLE DB Driver 18 for SQL Server®" and installed the latest *"OLE DB Driver 19.0 for SQL Server"*. Testing the connection using OLE DB Driver 19 driver then getting the following connection error:
------------------------------------------------------------------------
## OLE DB Driver 19 for SQL Server Data Link Error
\[Microsoft OLE DB Driver 19 for SQL Server\]: Client unable to establish connection
\[Microsoft OLE DB Driver 19 for SQL Server\]: SSL Provider: The certificate chain was issued by an authority that is not trusted.
Looks like opening a connection got failed. When it calls Open() method then it throws the above error.
My Code Snippet:
string connStr = string.Empty;
if (rbUseMSOLEDB.Checked)
connStr = "provider=MSOLEDBSQL19;";
else
connStr = "provider=SQLOLEDB;";
connStr += "Data Source=" + txtServer.Text + "; Initial Catalog=" + txtDBName.Text + "; User Id=" + txtUserName.Text + "; Password=" + txtPassword.Text + ";";
using (OleDbConnection con = new OleDbConnection(connStr))
{
con.Open();
con.Close();
}
Please help me to find out the root cause of this error.
**My Configuration Details as below:**
SQL Server Management Studio 15.0.18338.0
SQL Server Management Objects (SMO) 16.100.41011.9
Microsoft Analysis Services Client Tools 15.0.19205.0
Microsoft Data Access Components (MDAC) 10.0.19041.1
Microsoft MSXML 3.0 6.0
Microsoft .NET Framework 4.0.30319.42000
Operating System 10.0.19044
Note: With older version of Microsoft® OLE DB Driver 18 for SQL Server®" (18.6.3.0) connection is working using SQLOLEDB provider.
Regards,
Suresh Kaushik
[/INST]There is a breaking change in the Microsoft OLE DB Driver 19 for SQL Server. It requires a certificate.
Though it is possible to disable it via additional setting in the connection string:
**Use Encryption for Data=False**
Here is a sample of the entire connection string:
**Provider=MSOLEDBSQL19.1;Integrated Security=SSPI;Persist Security Info=False;User ID="";Initial Catalog=AdventureWorks2019;Data Source=.;Use Encryption for Data=False;**</s>
|
<s>[INST]AG & cluster failover during query execution
What will happen if during query execution (both distributed and non distributed) failover happens in
a. SQL clustering
b. AG group
Kindly help in understanding.
[/INST]It will result in a connection failure and the query will stop running as part of the controlled shutdown of services, all services are shutdown on one node and restarted on the another
If the reply above was helpful please mark as accepted answer so it can be helpful for other community members with same questions.</s>
|
<s>[INST]Msg 206, Level 16, State 2, Line 5 Operand type clash: int is incompatible with date
I am getting error ,
Msg 206, Level 16, State 2, Line 5
Operand type clash: int is incompatible with date
when i execute below query in my data,i am using sql server 2014
Declare @StartDate date='2022-02-01'
Declare @EndDate date='2022-02-05'
;WITH CTE AS
(
SELECT Contno,C.Entrydate,0 AS Opening_Weight,CASE WHEN C.Entrydate BETWEEN @StartDate AND @EndDate THEN ConWeight ELSE 0 END AS IN_Weight,
SUM(CASE WHEN I.Entrydate BETWEEN @StartDate AND @EndDate THEN IWeight ELSE 0 END)AS Issue_Weight
FROM Containerno C LEFT JOIN ConIssuance I ON C.CID=I.CID
WHERE (C.Entrydate < @StartDate AND I.Entrydate BETWEEN @StartDate AND @EndDate)OR C.Entrydate BETWEEN @StartDate AND @EndDate
GROUP BY Contno,C.Entrydate,ConWeight
UNION
SELECT Contno,C.Entrydate,ConWeight-SUM(ISNULL(IWeight,0)) AS Opening_Weight,0 AS IN_Weight,0 AS Issue_Weight
FROM Containerno C LEFT JOIN ConIssuance I ON C.CID=I.CID AND ISNULL(I.Entrydate,0)< @StartDate
WHERE C.Entrydate < @StartDate
GROUP BY Contno,C.Entrydate,ConWeight
)
SELECT Contno AS Barcode,Entrydate AS IN_Date,SUM(Opening_Weight)AS Opening_Weight,SUM(IN_Weight)AS IN_Weight,SUM(Issue_Weight)AS Issue_Weight,
CASE WHEN SUM(Opening_Weight) =0 THEN SUM(IN_Weight)-SUM(Issue_Weight) ELSE SUM(Opening_Weight)-SUM(Issue_Weight) END AS Closing_Weight
FROM CTE
GROUP BY Contno,Entrydate
[/INST]Try replacing *ISNULL(I.Entrydate, 0)* with *ISNULL(I.Entrydate, ' ' )*.</s>
|
<s>[INST]Unable to connect SQL express DB instance via jdbc when database password contains back slash
I am trying to connect to SQL express DB instance via jdbc. DB password is "Passw0rd\\".
Here is the code I am using:
String url ="jdbc:sqlserver://hostname:2638;instanceName=SQLEXPRESSSYMC;integratedSecurity=false;encrypt=true;trustServerCertificate=true";
String password = "Passw0rd\\";
try
{
System.out.println("url:" +url );
System.out.println("Password:"+password);
Connection conn = DriverManager.getConnection(url , "DBA", password);
System.out.println("connected");
}
catch (Exception e)
{
e.printStackTrace();
}
I get following exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'DBA'. ClientConnectionId:3be3d544-73d3-4710-aa4e-dfe78b6dcbb1
com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:262),
com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:283),
com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:129),
com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:37),
com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:5233),
com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:3988),
com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:3932),
com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7375),
com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:3206),
com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2713),
com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2362),
com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2213),
com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1276),
com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:861),
java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677),
java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
If I set DB password which uses back slash character but not as an end character then it works. e.g
String password = "Passw0rd\a";
Please let me know how to resolve this?
[/INST]Some special character like bask slash, can be used as escape characters, this need to be validated in case it is interpreted as an escape character, so when using it, it often leads to errors, it needs to ensure that they are validated as string literals and not escape characters, for simple, it is recommended not to use bask slash</s>
|
<s>[INST]SQL AG Listner behavior during Failover
Hello All,
Hope everyone doing good during this pandemic.
We have a AG with 2 replicas in same subnet, AG listener configured and able to connect using Listener name.
Test Case 1 : We have connect SQL server using AG Listener name from SSMS executed a script with cursor ( Created to run for long time) in the background initiated a Manual and automatic failover (Stopped SQL services on Primary Replica).
Observation : Our ongoing Query failed with below error, Is there any settings \ additional setup need to continue ongoing transactions or it's limitation of AG where ongoing transactions will killed \ Rollbacked
**Msg 596, Level 21, State 1, Line 0
Cannot continue the execution because the session is in the kill state.
Msg 0, Level 20, State 0, Line 0
A severe error occurred on the current command. The results, if any, should be discarded.**
Note : We are facing same issue with Application also, When ever failover happened it's going to login page with server error.
Sample Connection String :
**Data Source=tcp:AGName,1234;Database=DB_name;User Id=loginname;Password=password;**
[/INST]Any queries/batches that are running when you fail over will indeed succumb. You are pulling the carpet for them, so there is not much you can do. The state of the session is in the memory of the SQL Server instance you are failing over from.
If clients are common running long-running queries, they may need to be rewritten so that they automatically retries in cases of a failover.
A client the connects correctly to the listener, but is not running anything when the failover sets in, should notice anything.</s>
|
<s>[INST]Compare the amount with previous timeline
I have to compare the profit and Loss amount of the current timeline with the very previous current timeline. The result should show if proft and Loss data is different of current timeline with the very previous timeline from current timeline. The key field of this table is R1,TP,O1,Date1.
Create table #R1 (CL char(10), R1 char(10), TP char(10), O1 char(10), Date1 datetime, amount1 numeric(10,2), profit int , Loss int)
Insert into #R1 values ('111','AA','AAAA','11','2021-01-01', 12.35,1000, 10)
Insert into #R1 values ('111','AA','AAAA','11','2022-01-01', 15.55,1000, 10)
Insert into #R1 values ('111','RA','AAAA','11','2021-01-01', 16.99,1000, 10)
Insert into #R1 values ('111','RA','AAAA','11','2022-01-01', 17.99,500, 10)
Insert into #R1 values ('111','AB','AAAA','11','2021-01-01', 12.35,1000, 10)
Insert into #R1 values ('111','AB','AAAA','11','2022-01-01', 15.55,1000, 10)
Insert into #R1 values ('111','BA','AAAA','11','2021-01-01', 16.99,1000, 10)
Insert into #R1 values ('111','BA','AAAA','11','2022-01-01', 17.99,500, 9)
Select * from #R1 order by r1, Tp, o1, Date1
Desired output:
CL R1 TP O1 Date1 amount1 profit Loss
111 BA AAAA 11 2022-01-01 17.99 500 9
111 RA AAAA 11 2022-01-01 17.99 500 10
[/INST]Check one of solutions:
;
with Q as
(
select *,
lag(profit) over (partition by CL, R1, TP, O1 order by Date1) prev_profit,
lag(loss) over (partition by CL, R1, TP, O1 order by Date1) prev_loss,
lead(Date1) over (partition by CL, R1, TP, O1 order by Date1) next_Date
from #R1
)
select CL, R1, TP, O1, Date1, amount1, profit, Loss
from Q
where next_Date is null and (prev_profit <> profit or prev_loss <> loss)
order by r1, Tp, o1, Date1</s>
|
<s>[INST]alter column
alter column in large table takes lot of time and sometimes does not complete(needs restart of server). Please help me by informing which data type conversions execute instantly and which conversions take time.[/INST]There are three levels of ALTER TABLE ALTER COLUMN:
1. Pure metadata change.
2. Metadata change, but needs to be validated.
3. Table has to be rebuilt entirely.
Pure metadata changes are when you are making a varchar, nvarchar or varbinary column longer.
But if you change to a datatype with a different format or size, the table has to be rebuild. For instance int to bigint requires the table to be rebuilt. Same goes for changing from char(4) to char(6).
The middle ground, when validation is required is when you change a column from permitting NULL to be NOT NULL. Validation is also required when you make a varchar, nvarchar or varbinary column shorter. The validation is required to make sure that there no values that violate the new definition.</s>
|
<s>[INST]What queries to tune first and why?
Hi All,
This is in regards to server slowness. If I had to tune top 10 resource consuming queries which ones has to be targeted first and why?
- Long running queries / Blocked queries / High Duration
- I/O consuming queries / memory consuming queries
- CPU consuming queries
- User specific chosen queries
Also, what high values we need to consider for thresholds to determine for long running . high cpu , high reads/high writes?
Regards,
Sam
[/INST]Start with the easy ones. That is, if you identify a query that would benefit from an index, add that index. If you see a query which written in such a way that Index Seek is not possible, but you easily can rewrite it, do that.
From your list above, queries singled out by users are probably the ones you should start with, since these are likely to cause most pain. If a background process runs a query for fifteen minutes, no one may suffer directly, even if the query could complete in 15 seconds with some tuning. Then again, that background query may take resources, so tuning it may still pay off.
I usually work from Duration, but I keep an eye on the ratio CPU / Duration. If this one is low, below 0.2 or so, I assume that the query is a victim of blocking. In these cases, I may go after the blockers instead.</s>
|
<s>[INST]Error converting data type varchar to numeric.
i am getting error
Error converting data type varchar to numeric.
Create table #Containerno (CID int,ConWEight varchar(50),Container_Rate decimal(10,4),Trucking_Charges decimal(10,4),)
insert into #Containerno values(444,' ', 22.01,5555)
SELECT convert(numeric(10,2),(isnull(c.ConWeight,0)*c.Container_Rate)+c.Trucking_Charges) as Invoice_Amount
FROM #Containerno c
[/INST]ISNULL: Replaces **NULL** with the specified replacement value.
However in this sample, 'ConWEight' is blank value instead of NULL. Therefore you could use NULLIF to turn ' ' to NULL first and then use ISNULL, like this:
SELECT convert(numeric(10,2),(isnull(nullif(c.ConWeight,''),0)*c.Container_Rate)+c.Trucking_Charges) as Invoice_Amount
FROM #Containerno c</s>
|
<s>[INST]Minimum permissions or role to create a new database from backup
How can I set up a minimum server role to create a new database (by restore from a backup file)?
I note that there is a server role called "DBCreator" and it is possible to create a custom server role with "Create any database".
These looked promising but in the documentation seems like these have the ability to **drop any database** as well. So not good. Could I prevent this role from dropping databases?
[/INST]Could I prevent this role from dropping databases?
No, one cannot grant, deny, or revoke permissions from dbcreator and other special fixed server roles.
A custom server role with the minimal `CREATE ANY DATABASE` permission will allow users to restore to a new database name but not restore existing databases, unless permissions to do so are provided by other means (e.g. as the database owner).
CREATE SERVER ROLE custom_dbcreator;
GRANT CREATE ANY DATABASE TO custom_dbcreator;
ALTER SERVER ROLE custom_dbcreator
ADD MEMBER SomeLogin;
Note that since the user account who restored the database will be the database owner after the restore, they will be able to restore the database even though it exists. If your requirement is that should not be allowed, the database owner (authorization) will need to be changed after a restore by custom role members.</s>
|
<s>[INST]Invalid column name
Hi,
I have the following code
SET @sqlCommand = '
select
*
from
#temptable
where
SALES_OFFICE not in
(SELECT [SalesOfficeCode] from ' + (SELECT schema_name FROM #schema WHERE ROWNUMBER = @Init)
+ '.[DimSalesOffice]) and sales_division = ' + (SELECT schema_name FROM #schema WHERE ROWNUMBER = @Init)
However I am receiving the error
> Invalid column name
The error seems to be related to the last part when is doing the comparison
sales_division = ' + (SELECT schema_name FROM #schema WHERE ROWNUMBER = @Init)
The part above that pulls the row value fine? Any ideas?
[/INST]Print our your sql string.
My guess is this:
and sales_division = ''' + (SELECT schema_name FROM #schema WHERE ROWNUMBER = @Init)+''''</s>
|
<s>[INST]Machine having Windows Defender feature but not having System Center Endpoint Protection installed.
Hello,
I am trying to list the machine having Windows Defender feature but missing System Center Endpoint Protection Application:
===========================================================================
select distinct sys.Name0, gsof.Name0,
CASE
WHEN gsof.InstallState0 = '1' THEN 'Enabled'
WHEN gsof.InstallState0 = '2' THEN 'Disabled'
WHEN gsof.InstallState0 = '3' THEN 'Absent'
ELSE 'Unknown'
END AS FeatureStatus
from v_R_System sys
Join v_FullCollectionMembership fcm on fcm.ResourceID = sys.ResourceID
inner join v_GS_OPTIONAL_FEATURE gsof on gsof.ResourceID = sys.ResourceId
where
gsof.Name0 = 'Windows-Defender' and gsof.InstallState0 = '1'
and
fcm.CollectionID = 'UCP00020'
and sys.ResourceID not exists (
Select v_GS_ADD_REMOVE_PROGRAMS_64.ResourceID from v_GS_ADD_REMOVE_PROGRAMS_64
where v_GS_ADD_REMOVE_PROGRAMS_64.DisplayName0 like '%System Center Endpoint Protection%')
and
sys.ResourceID not exists (
Select v_GS_ADD_REMOVE_PROGRAMS.ResourceID from v_GS_ADD_REMOVE_PROGRAMS
where v_GS_ADD_REMOVE_PROGRAMS.DisplayName0 like '%System Center Endpoint Protection%'
)
order by gsof.Name0
===========================================================================
I always got 0 result which is wrong as I know at least 2 machines with Windows Defender feature not having SCEP installed.
What is wrong?
Thanks,
Dom[/INST]There is a common trap with NOT IN: it will not return any row if the subquery returns a single NULL value. Not that I know whether v_GS_ADD_REMOVE_PROGRAMS.ResourceID ever can be NULL. But if it can be, you can avoid this trap by adding the condition `WHERE v_GS_ADD_REMOVE_PROGRAMS.ResourceID IS NOT NULL` to the subquery.
Although, there can certainly be more issues with your query. As Ronen pointed out, we don't know the tables. With the tags you added, you are reaching people who know SQL Server well. However, it seems that you are using System Center, and you may be better off asking a question with the appropriate `mem-` tag. (mem for Microsoft Endpoint Manager.) The folks who monitor those tags, are likely to know the data model of your database, so they can easier spot logical errors than we can do. (I for one have never worked with System Center.)</s>
|
<s>[INST]Log full 9002 error
Hi Experts.
I want to call a sql agent job when 80% of the Transaction Log file is full. I wanted to do some data collection when the log is getting full.
How to do it?
Using SQL 2017 EE.
Thanks,
Bob[/INST]You can get the fullness of the transaction log from yourdb.sys.dm_db_log_space_usage. There is no way you can tie an alert to it to start a job. But you could run a job every minute that checks the log size and starts to perform data collection.
Beware that the percentage value can change quickly in both direction. Autogrowth may kick in which increases the size of the log, and as a consequence the percentage may go down for a while.</s>
|
<s>[INST]It's good pratics to use exists before an update?
Hello,
as a title, I ask if it is a good idea to check if a record with a certain value exists first, before updating that record, because if the check is not done the update does nothing so it does not give side effects, so what is the best practices?[/INST]No. Checking to see if a record exists, and then updating the existing record causes 2 scans of the table. There is never a reason to do that. If you need to know if a record was actually updated you can use @@ROWCOUNT.</s>
|
<s>[INST]domain AD account for sql server service change.
hi Folks,
We use AD account as a sql server service account , my question is can we alter AD account like password change or change properties of this account without restarting sql server service?
For example if i change AD account passowrd that is used as a service account for sql server, do i need to restart sql server services? What happens if i dont set new password in the "log on" properties of sql server and agent service however i change password for this account at AD level?[/INST]What happens if i dont set new password in the "log on" properties of sql server and agent service however i change password for this account at AD level?
Nothing will happen when you change the password. But if you don't replicate the change in SQL Server Configuration Manager, SQL Server and Agent will not start next time you try to start them.
You don't have to restart the services because you change the passwords. However, it may be a good idea to do this to verify that you have entered the password correctly. Else you could have a stressful situation if SQL Server crashes and then don't start because of the wrong password.</s>
|
<s>[INST]SQL Server backup suddenly extremly slow
Since some days, my MS SQL Server database backup runs extremely slow.
I am running an SQL Server 2019 instance on a virtual server with a SSD drive. The database size is about 18 GB and the backup normally runs in 15 minutes, directly to a network USB drive. Suddenly the backup takes up to 5 hours. The database contains 2 filestream tables, one table with 70000 documents. The filestream data is about 16 GB in size.
Now when I run the backup it sometimes starts fast and writes for example 10 GB in 5 minutes, but then gets very slow and can even get stuck.
What I tried so far:
- restored the database to a development environment and tried a backup from there - same problem with slow performance
- used a different backup location
- checked SSD write / read speed of the server
- restarted SQL service / instance
- a sheduled task from SQLBackupAndFTP got stuck after 3 hours with 2 GB written, a manual task runs succesful but takes 1 hour to finish
- backed up a different database on the same instance with 3 GB in 20 seconds
I assume, that there is a problem with the database itself or with some data inside.
What possibilities do I have to find out the reason for this behavior?
Thank you
Michael[/INST]There was a thread recently where the poster also had problems with slow backup in Filestream. In that case, the poster was able to get good speed by configuring the antivirus to not check the filestream area.</s>
|
<s>[INST]Possible Bug in SQL Server 2014,2019 With Temp tables
I Have this Query (Minimal reproduction)
CREATE TABLE [Product] ON [PRIMARY]
GO
create table #TmpProduct
(
ID int
)
go
INSERT INTO Product([Num],[Name],[Price]) values(1,'P01',4);
INSERT INTO Product([Num],[Name],[Price]) values(2,'P02',41);
INSERT INTO Product([Num],[Name],[Price]) values(3,'P03',55);
INSERT INTO Product([Num],[Name],[Price]) values(4,'F04',21);
INSERT INTO Product([Num],[Name],[Price]) values(5,'F05',6);
INSERT INTO Product([Num],[Name],[Price]) values(6,'S06',1);
go
INSERT INTO #TmpProduct(ID) SELECT Num FROM Product WHERE Num < 3;
UPDATE Product SET Price =0 WHERE Num IN (SELECT *Num* FROM #TmpProduct);
I Have 2 problems
1- I Can run UPDATE Query Without any error, although Num Column is not part of TmpProduct !!!
2- With this query all Rows in Product table are set to 0!!! this is very dangerous
Nb: SQl server 2014 Version is 12.0.6024.0,
2019 15.0.2000.5
[/INST]This is working as designed.
1. When you reference a column name in a subquery (Num in your case) SQL firsts looks for that column in the tables in your subquery (#TmpProduct in your case). If it doesn't find that column in the subquery tables it then looks for that column in the outer query (Product in your case). If it finds it there it then uses that column. You will only get an error if that column name is not in the tables of either the inner subquery or outer query. Since Num is in Product you do not get an error. This is the way SQL has always worked.
2. Since Num is in Product and not \#TmpProduct, SQL uses the Num in Product. So your query effectively becomes
UPDATE Product SET Price =0 WHERE Num IN (SELECT Num FROM Product);
And since that is true for every row in Product, Price gets set to zero for every row.
You want to get into the practice of always explicitly specifying the table each column is in (particulary when the query references more than one table). So write your query like
UPDATE Product SET Price =0 WHERE Product.Num IN (SELECT \#TmpProduct.Num FROM \#TmpProduct);
If you do that, you will be given an error for invalid column name 'Num' and the query will not run.</s>
|
<s>[INST]Slicing time periods by related time periods
Hi,
I have 2 tables , the first one contain all data , and the second contain the same data but aggregate.
Table1
DD_S DF_S id_Prod
20190101 20190601 10
20190601 20190901 10
20190901 20200701 10
20200701 20211001 10
20211001 20211101 10
20211101 20220401 10
20220401 20291231 10
Table 2
DD DF identifier id_Prod
20190101 20211001 5 10
20211001 20211101 4 10
20211101 20291231 5 10
I want to retrieve the column identifier from table2 in the table 1 by slicing the period as bellow what i want :
DD_S DF_S id_Prod identifier DD DF
20190101 20190601 10 5 20190101 20211001
20190601 20190901 10 5 20190101 20211001
20190901 20200701 10 5 20190101 20211001
20200701 20211001 10 5 20190101 20211001
20211001 20211101 10 4 20211001 20211101
20211101 20220401 10 5 20211101 20291231
20220401 20291231 10 5 20211101 20291231
Any idea how can i do that ? Thanks for help !!
[/INST]SELECT a.[DD_S]
,a.[DF_S]
,a.[id_Prod]
,b.[identifier]
,b.[DD] , b.[DF]
FROM table1 a
join table2 b
on a.[id_Prod]=b.[id_Prod]
and (a.[DD_S]>=b.[DD] and a.[DF_S]<=b.[DF])</s>
|
<s>[INST]SQL server SPLIT String
Can someone help me with a function to get a part of the text from this string?
L=CTV,OU=CALUBCO,OU=testext,DC=Test,DC=com
I need the value `OU=CALUBCO` from the text above.
Thanks in advance!
[/INST]Please try the following solution based on tokenization via JSON.
It will work starting from SQL Server 2016 onwards.
We are looking for the 2nd token in the comma separated list of tokens.
JSON array starts from 0 (zero).
**SQL**
-- DDL and sample data population, start
DECLARE @tbl TABLE (tokens VARCHAR(1000));
INSERT INTO @tbl (tokens) VALUES
('L=CTV,OU=CALUBCO,OU=testext,DC=Test,DC=com');
-- DDL and sample data population, end
SELECT Result = JSON_VALUE(S,'$[1]')
FROM @tbl
CROSS APPLY (VALUES ('["' + REPLACE(STRING_ESCAPE(tokens,'json'),',','","') + '"]')) AS B(S);
**Output**
| Result |</s>
|
<s>[INST]How to export tables and data from SQL Server 2017
Hi guys,
I need to export data and tables from SQL Server 2017 with Management Studio. I wonder if it is possible export from server and import into my local SQL express?
Thanks in advance.[/INST]One option is to right-click the database in Object Explorer, and select Tasks->Generate scripts. When you come to the page where you select the target for the script, click the Advanced button which give you lots of options. Change Script Schema-Only to include data as well.
Another way to copy a database is to use BACKUP/RESTORE, but this assumes that you can get hold of the backup file, which may not be simple if you have the database in a hosted environment.</s>
|
<s>[INST]Continue running SQL even after an error in where clause
All,
The last statement in this code block gives me the DATE conversion error. My requirement is to run the statement even after the last statement fails. How can I achieve this?
SELECT USERID FROM IMSIDENTITYPRE
WHERE IDENTITYSTATUS IN ('ACTIVATED','INITIATED','SUSPENDED')
AND AUTHORITATIVESOURCE IN('WD', 'SP' )
AND USERID NOT IN (SELECT IDENTITYUSERID FROM WDIdentityPRE)
AND USERID NOT IN (SELECT GDD FROM ADIdentityPRE)
AND CAST(AssignmentStartDate AS DATE)<=GETDATE()
[/INST]Adding to Viorel 's answer, `TRY_CAST` (or `TRY_CONVERT`) will return `NULL` when the proported date column value cannot be converted to date. The predicate `TRY_CAST(AssignmentStartDate AS DATE)<=GETDATE()` will not be satisfied for invalid dates because the result is UNKNOWN instead of true of false.
SELECT USERID FROM IMSIDENTITYPRE
WHERE
IDENTITYSTATUS IN ('ACTIVATED','INITIATED','SUSPENDED')
AND AUTHORITATIVESOURCE IN('WD', 'SP' )
AND USERID NOT IN (SELECT IDENTITYUSERID FROM WDIdentityPRE)
AND USERID NOT IN (SELECT GDD FROM ADIdentityPRE)
AND TRY_CAST(AssignmentStartDate AS DATE)<=GETDATE();
Consider changing the `AssignmentStartDate` column to a `date` data type to ensure invalid dates cannot be stored. This will provide data integrity, improve performance, and reduce storage needs.</s>
|
<s>[INST]Help with the query
Hi there,
I have two tables Appointments and NAP.
I need to join them with logic below -
appointment \[(appt location starts with 'D&A') & MRN & Appt Date\] = NAP \[(SU name starts with 'D&A') & MRN & Appt Date\]
How to do the first part in SQL Server query -
appointment
left outer join NAP
on
**left(app.\[Appt Location\],3) and left(nap3.\[Service Unit Name\],3) ='D&A'**
appointment .MRN= NAP .MRN and
appointment .\[Appt Date\] =NAP .\[Service Date\]
Thanks
[/INST]Try changing the line to:
*appointment.[Appt Location] LIKE 'D&A%' and nap.[Service Unit Name] LIKE 'D&A%'*</s>
|
<s>[INST]Rollback not completing.
Greetings.
I killed a spid 8 hours ago and it's still not done. Stuck in KILLED/ROLLBACK state, the wait_type is mostly PAGEIOLATCH_EX, the Reads/ Writes are still going up, and the sproc was from a user DB, but the statement it's been stuck on is in tempDB due to temp tables.
What's really annoying is the query below still shows 0% complete.
Where so I go from here?
select command,percent_complete,'elapsed'=total_elapsed_time/60000.0,'to complete' = estimated_completion_time /60000.0 from sys.dm_exec_requests where
command like '%ROLLBACK%'
[/INST]There is not much you can do, you have to wait until the rollback finished.
Even if you restart SQL Server, the rollback process will continue on startup.</s>
|
<s>[INST]Get data from yesterday
Hi,
I want to get data against yesterday
data table.[full_date]
2000-01-11 00:00:00.000
How would I say where full_date = yesterday?
Thanks
Chris[/INST]Yesterday is today - 1 day
WHERE full_date = DATEADD(day, -1, GETDATE())
However chances are your column is actually a DATETIME and therefore the equality check will fail because the timestamps are different so you need to filter out that as well. Different ways of doing it. If the `full_date` column has all the times set to midnight then you need only remove the timestamp from yesterday.
WHERE full_date = DATEADD(day, -1, CAST(GETDATE() AS DATE))
However if your `full_date` also has timestamps then a date diff is needed. Perhaps something like this (not fully tested).
WHERE DATEDIFF(day, full_date, DATEADD(day, -1, GETDATE())) = 0</s>
|
<s>[INST]Update the numeric in Decimal
Hello, I have to replace the number in decimal area with Zero if decimal value is less than 0.99
Data:
7889.00008000
7828.00800000
7363.00000060
7363.99999990
Expected output: --All decimals should be Zero except if decimal value is less than 0.99
7889.00000000
7828.00000000
7363.00000000
7363.99999990[/INST]Declare @Sample Table(Nbr decimal(15,8));
Insert @Sample(Nbr) Values
(7889.00008000),
(7828.00800000),
(7363.00000060),
(7363.99999990);
Update @Sample
Set Nbr = Floor(Nbr)
Where Floor((Nbr*100)) % 100 <> 99;
Select Nbr From @Sample;</s>
|
<s>[INST]Differences between ALTER ANY LOGIN & securityadmin Server level role?
Hello, what are the differences between ALTER ANY LOGIN & securityadmin Server level role?
Think I have an idea that securityadmin Server level role probably has higher permissions but would like to know more specifics.
Thanks in advance.[/INST]There is an enormous difference. Securityadmin grant server-level permissions to other users. You cannot do that with ALTER ANY LOGIN only.
The demo below illustrates. As the script is given the GRANT CONTROL SERVER command fails. Comment out GRANT ALTER ANY LOGIN and activate ALTER SERVER ROLE instead, and the GRANT fails. Yet, there is no difference in the output from fn_my_permissions.
USE master
go
CREATE LOGIN testsecadmin WITH PASSWORD = 'TeMporrrray'
CREATE LOGIN otherlogin WITH PASSWORD = 'Klklklklklkl'
go
GRANT ALTER ANY LOGIN TO testsecadmin
go
EXECUTE AS LOGIN = 'testsecadmin'
go
SELECT * FROM sys.fn_my_permissions(NULL, NULL)
GRANT CONTROL SERVER TO otherlogin
go
REVERT
go
DROP LOGIN testsecadmin</s>
|
<s>[INST]'SDAAAKLL001' expected result
I want, before inserting into table #Containerno ,check Contno against (Level_Four_ID and Loc_ID column) ,if value exist against (Level_Four_ID and Loc_ID column) then add 1 else SDAAAKLL001,from table #Containerno
create table #ConCatagory (Cat_ID int ,Cat_Name varchar(50),Alias_Name varchar(50))
Insert into #ConCatagory values (1,'Akber','AAA')
create table #tbl_location (Loc_ID int ,Loc_Name varchar(50),Alias_Name varchar(50))
Insert into #tbl_location values (47,'Internal','SD')
create table #tbl_Account_L_Four (Level_Four_ID int ,Level_Four_Name varchar(50),Sup_code varchar(50),Cat_ID int)
Insert into #tbl_Account_L_Four values (2111006 ,'Kend Lal','KLL',1)
Create table #Containerno (CID int,Contno varchar(50),Level_Four_ID int,Loc_ID int)
Insert into #Containerno values (1111,'SDAAAKLL001',2111006 ,47)
Output
SDAAAKLL001
SD =will take from #tbl_location column Alias_Name.
AAA = will take from #ConCatagory column Alias_Name
KLL =will take from tbl_Account_L\_Four column Sup_code
001 = will be auto generated
I tried below query which is not giving me output when i pass Loc_ID parameter
select concat(c.Alias_Name,t.Sup_code, L.Alias_Name,
format(isnull(cast(substring(n.Contno, len(c.Alias_Name) +len(t.Sup_code) + len(L.Alias_Name) + 1, len(n.Contno)) as int), 0) + 1, '000')) as Barcode
from #tbl_Account_L_Four t
left outer join #ConCatagory c on c.Cat_ID = t.Cat_ID
left outer join #Containerno n on n.Level_Four_ID = t.Level_Four_ID
left outer join #tbl_location L on L.Loc_ID=n.Loc_ID and n.Contno like concat( c.Alias_Name,t.Sup_code, L.Alias_Name, '[0-11]%')
where t.Level_Four_ID = 2111006 and L.Loc_ID=47
[/INST]Check one of possible solutions:
select
concat(p, format(isnull(max(try_cast(stuff(n.Contno, 1, len(p), '') as int)), 0) + 1, '000')) as NewContno
from #ConCatagory c
inner join #tbl_Account_L_Four a on a.Cat_ID = c.Cat_ID
cross join #tbl_location L
cross apply (values (concat(L.Alias_Name, c.Alias_Name, a.Sup_code))) P(p)
left join #Containerno n on n.Level_Four_ID = a.Level_Four_ID and n.Loc_ID = L.Loc_ID and left(n.Contno, len(p)) = p
where a.Level_Four_ID = 2111006 and L.Loc_ID = 47</s>
|
<s>[INST]Change NT service user with domain account
Hi all,
I have a local instance (sql agent, engine and SSIS) on SS 2017 which have been registered without any domain user.
Now, I have these 3 new domain users (ad-hoc for all sql services) I would like to to know what precautions on permissions must I take to allow everything to work.
I would not like to restart the SQL instance and find myself orphaned of some write permissions.
In SQL Server configuration manger I'll change the user of each service.
Thanks, ALEN[/INST]That all depends on what permission etc you have granted to the current service accounts and also to the machine account. And here I'm more thinking of Windows permissions than permission in SQL Server.
As for the permissions needed to running SQL Server - no worry, SQL Server Configuration Manager will take care of that. But if you have granted access to the machine account on a file share to permit SQL Server to write backups there or read files for BULK INSERT, you will update those permissions to permit the new service accounts.
In short, you need to have your server(s) documented.</s>
|
<s>[INST]convert string to date
hi
I have a date in below format
'2020-08-17T16:28:46' as string
want to convert in date
please help
i am trying as below
convert(DATETIME,format(insta_map_date,'dd-MMM-yyyy'),103))
the error is `Argument data type varchar is invalid for argument 1 of format function. Severity 16`
please help
but with error
[/INST]It's a simple as this:
SELECT convert(datetime, '2020-08-17T16:28:46')
This is one of the safe formats, which will always be interpreted the one and the same, no matter the setting for DATEFORMAT.</s>
|
<s>[INST]After shrinking the log file the log file size has been increasing
Dear All,
I have database more then 20 millions data, I wanted the shrink log file.
after shrinking the log file the log file size is increasing.
I am using SQL server 2012 Express Edition
DB Name Log_size(MB) Row_size(MB) TOtal_size(MB) Total_Size(GB)
MYDb 97227.38 885.38 98112.75 95.81
Please suggest me the appropriate solutions.
Thanks,
Sunil[/INST]Shrinking the transaction log will cause fragmentation on the log file, and it might cause performance issues if the transaction log is spread out on different parts of a physical disk.
if you want to use less disk space for the transaction log, you should run the transaction log backup more than instead of shrinking the transaction log.
There are two good ways to reduce log file size:
1. regular Log file backups, the log file will reuse it's space after each log backup and won't grow indefinitely
In Full Recovery Model, your transaction log will grow until you take a backup of it. You need to take the T-Log Backup at a regular interval.
2. use the Simple recovery model, this way, you will not have extra ordinary growth of your log file.</s>
|
<s>[INST]AlwaysON cluster, the gMSA for SQL server service account should not be restarted automatically
I constructed a SQL Server 2016 cluster with two nodes and two SQL instances (SQL2016 and SQL2019). There are no issues with using an Active Directory user account as a SQL server service account. It's an ideal match.
When I switch the SQL server service account on SQL2016 and SQL2019 to a gMSA account and then restart the SQL service, AlwaysON operates normally.
After rebooting one node, it was revealed that the SQL server service running under the gMSA service account did not start immediately. Nevertheless, if I manually start the service, it starts and operates normally; nevertheless, the start type remains automatic.[/INST]My best guess is that there has been a hiccup in getting in touch with the AD in order to confirm the gMSA. You could try to set up SQL Server such that it starts automatically every time (Delayed). It is only available in the Services applet, and it is a one-time use function.</s>
|
<s>[INST]Using a new copy of SSMS: Where do I specify the access (IP) for a remote database?
On my old computer (Windows 10 laptop) I can use SSMS to access the local SQL database and a remote database identified as "DB". DB uses SQL Server authentication so I enter a userid and password and I can access the remote database with SSMS without problems.
I am setting up a new computer (Windows 11 PC), and I've set up SQL Server and SSMS, everything works correctly with the local database, I had no problem creating copies of the old local databases on the new computer. So far so good.
Where do I tell SSMS or Windows 11 how to find "DB". I know the IP address of the remote SQL server, and of course I have the username and password, but I don't how to tell my new computer that DB = this IP address (and whatever else I might need to tell it). I can't find anywhere to give this information, there must be somewhere in SSMS or in W11, but where?
Thank you, Robert.[/INST]but I don't how to tell my new computer that DB = this IP address
to be true, I don't understand a single word or what your issue is?
Databases don't have a IP address, server do.
In SSMS server login dialog enter under "Server name" the server name or IP address, your SQL credentials and go.
What happens then / which may error message do you get?</s>
|
<s>[INST]SQL Server Express localdb security
We were developing an application within .NET that would: read in data (generally in a text or csv format); run some analyses; and generate results/reports from the data. We were using SQL Server Express localdb to create temporary DBs and to perform the analyses. This would all happen locally on one's computer/laptop. Our security team was worried about the possibility of a SQL injection attack. Is this a valid concern? Sorry if I have not provided enough detail and am happy to clarify as needed. [/INST]Sql injection is not related to where the database is stored but rather how you construct the sql statements. But maybe they mean the user could modify the data to change the report, but a malicious user could just modify the output.</s>
|
<s>[INST]What gets logged in Bulk logged recovery model
In Bulk logged recovery model, what gets logged- page allocations or extents allocations?
Suppose I inserted 2 million records into a table t1 using INSERT INTO. If i take full backup and restore it, will the restored database contain both t1 and the data?[/INST]But in bulk logged recovery model, data inserts are not logged , right? So how will the restored database contain data?
Well, you asked about a *full* backup, so there is not even any relation to what is being logged in the transaction log.
But to address your concern. let's say that you do this:
1. Take a full backup.
2. Create your table and add data to it in a minimally logged operation.
3. Take a transaction log backup.
4. Restore the full backup with NORECOVERY.
5. Restore the transaction log backup. (WITH RECOVERY this time).
Will the data in the table be there after the restore? The answer is yes. This because in step 3, all those pages in these extents for which SQL Server only logged the allocation of to the transaction log are written to the backup. SQL Server knows which pages this is, because there is a special bitmap page with this information.
The one thing you cannot do is to restore the transaction log and say "Hey, SQL Server stop at this point, just before I inserted the data". When you are in bulk_logged recovery, you need to restore transaction-log backups in whole, there is no point-in-time recovery.
Overall, there is never a situation where you take a backup (full, differenital, or log), and restore the backups, and you don't have the same data as you had originally. That would be a major bug. (OK, so there is one exception: there is corruption due to bad hardware somewhere along the line.)</s>
|
<s>[INST]'Could note execute Sp_replcmds' blocking the entries.
One morning; got message from one of the replicated locations (target database) that latest entries aren't seen (from source database); found that message was prompted as 'could not execute sp_replcmds'. After checking; fired the command as 'sp_replrestart' to start replication; after it replication started and latest entries got synced; however the entries from start of issue of 'could not execute sp_replcmds' until firing of sp_replrestart did not got replicated to target database.
Can this situation be avoided. Also, is there a way whereby; the entries from start of this message until replication restart do not get skipped and get synced to target database. Thanks in advance.[/INST]You should not ever run sp_replrestart. That is an internal stored proc which is used in by the system.
sp_replrestart has reset the current pointer to say everything was delivered. The only way to fix this now, is to reinit the subscription.</s>
|
<s>[INST]Assigning same status same row group
Hi there, just need to assing always the same value (1) regardless if it has 0 or NULL.
DECLARE @T1 AS TABLE(ID2 SMALLINT, BUILDING INT, BUILDING_STATUS BIT)
INSERT INTO @T1(ID2,BUILDING, BUILDING_STATUS)
VALUES(1,5671,0),(2,5671,NULL), (3,5671,1),(4,5673,1),(5,5674,2)
SELECT * FROM @T1
Output should be:
1 5671 1
2 5671 1
3 5671 1
4 5673 1
Thanks a lot,
[/INST]Try another query:
SELECT ID2, BUILDING, max(cast(isnull(BUILDING_STATUS, 1) as int)) over (partition by BUILDING) as BUILDING_STATUS
FROM @T1
order by ID2
Although, it is not clear what to display if all values in a group are *NULL*.</s>
|
<s>[INST]How about SSDT 2015 after SQL Server 2016 upgrade to SQL Server 2017 ?
I am doing in place upgrade for SQL Server 2016 to SQL Server 2017.
And SQL Server upgraded without issue.
But I have concern on the SSIS package setup in SQL Server Agent Jobs.
Do I need to upgrade the SSIS package ? Or it still able to execute ?
The SSIS package were build by SSDT 2015. Do I need to uninstall SSDT 2015 and install SSDT 2017 ?[/INST]Because rebuild by SSDT 2017 take time
I have packages with several hundred task and a rebuild (compile) takes may 5 seconds.
I didn't meant re-create, just & simply rebuild.</s>
|
<s>[INST]SQL Server 2016 Table Column Width
I have a customer using Rockwell Automation's Transaction Manager to pass some data from a PLC into an MS SQL Express 2016 database. The data types are set to real in the columns in question. Each column in the table is filled with data up to eight total characters, one including the decimal point. As these numbers have increased over time I have lost placeholders to the right of the decimal each time one was added to the left side. (For example: Early data points read in a format of 1000.000; however, as the value has grown they now look like 100000.0. ) I am trying to understand why these values are restricted to only eight characters. I assume that there is a way to address this in the table but I have been unable to find this. [/INST]the other values are smaller. Again, a `real` value is not stored a string inside the computer. It's stored as 32 ones and zeroes. What you see in SSMS is only textual representation to make it easier to read for humans.
Here is an example:
DECLARE @numberTable TABLE (r real NOT NULL,
f float NOT NULL,
d decimal(12,3) NULL)
INSERT @numberTable(r, f, d)
VALUES(0.123, 0.123, 0.123),
(1.123, 1.123, 1.123),
(12.123, 12.123, 12.123),
(123.123, 123.123, 123.123),
(1234.123, 1234.123, 1234.123),
(12345.123, 12345.123, 12345.123),
(123456.123, 123456.123, 123456.123),
(12345678.123, 12345678.123, 12345678.123),
(123456789.123, 123456789.123, 123456789.123),
(1234567890.123, 1234567890.123, NULL)
SELECT * FROM @numberTable
The `r` column shows fewer and fewer decimals as the numbers grow, and eventually it changes to scientific notation.
The `f` column is `float` which is a 64-bit floating-point value. For the numbers above, you still get three decimals, but if you keep on adding digits, you will lose decimals, and you will eventually get scientific notation in this case as well.
Both float and real are *approximate* data type. While you may see 1.123, the actual value is something else, something which can be expressed with a power of 2.
The `d` column is of the `decimal` data type which is an *exact* data type. The values you see on the screen are really the ones that are stored. (But, again, they are not stored as characters, they are stored as ones as zeroes according to some format.) However, you may note that I have a NULL value on the last row. If you would put this number into the `d` column, you would get an overflow error. The column is defined as `decimal(12,3)`, which means 12 digits whereof 3 are decimals. So while you don't lose any decimals, you have a hard upper limit. That limit does not have to be 12, though, 38 is the highest value you can choose.
If I understand your post correctly, this meter is akin to an odometer. In that case, it may make sense to save all digits, and in this case, `float` or `decimal` may be better choices than `real`. You will need investigate what is the maximum value this meter can produce to make the choice.</s>
|
<s>[INST]SQL Upgrade
In case of a Side by Side Upgrade i.e to migrate databases from SQL 2012 to SQL 2019 wherein a new VM is created , SQL 2019 Installed and databases migrated using backup and restore strategy. In this case if we do not change the backward compatibility no database(DMA) and application assessment is required for compatibility as will work in the same manner for SQL 2019 as was working for SQL 2012. Can you please advise if this is correct[/INST]You should never depend on the "compatibility level" setting. This does NOT make the version 100% compatible with previous versions. It only affects certain functionality to give you time to upgrade to the new functionality.
You should always test your application with new versions of SQL Server.</s>
|
<s>[INST]sql server Windows login that are part of AD group precedence
hello,
We are migrating our individual windows login ids to the ad group in sql server. While testing this, we added newly created AD group for corresponding teams with windows login ids. While testing this in SQL Server as a precaution we would like to keep windows id alongwith newly created AD group. Only thing we did was disable individual Windows Logins in SQL Server assuming those ids will get authenticated using AD groups in SQL Server.
However it seems if a windows id is part of a AD group and if we disable individual windows id, users are not able to login. So it looks like windows id takes precedence even though same id is part of AD group. Is there any way to keep windows id (disabled state) and ad group and test authentication through AD group?
Is there a better approach to do this?
thank you.
[/INST]I don't think you can avoid dropping the logins. I assume that you did ALTER LOGIN DISABLE?
The only thing you could lose if you drop these logins are their permissions. You could script the permissions and role membership before you drop the logins. Note that the individual databases are not affected.</s>
|
<s>[INST]Inner join with more than one on statment or two sets of variables
Just wondering if SQL server 2019 could do multi variable join in one inner join clause or do I have to use the where clause?[/INST]Here is a sample of 'Inner Join' ,hope it helpful.
create table #student(stu_id int,dep_id int,stu_name varchar(10));
insert into #student values(1001,1,'Tom'),(1002,1,'Bob'),(1003,1,'Mike');
create table #score(stu_id int,dep_id int,subject_id int,score int)
insert into #score values(1001,1,201,90),(1001,1,203,87),(1002,1,202,88),(1002,1,203,95),(1003,2,201,93),(1003,2,203,88)
create table #subject(subject_id int,subject_name varchar(20))
insert into #subject values(201,'Science'),(202,'History'),(203,'Math')
--query 1
SELECT A.stu_name,C.subject_name,B.score
FROM #student A INNER JOIN #score B ON A.stu_id=B.stu_id
INNER JOIN #subject C ON B.subject_id=C.subject_id
--query 2
SELECT A.stu_name,C.subject_name,B.score
FROM #student A INNER JOIN #score B ON A.stu_id=B.stu_id AND A.dep_id=B.dep_id
INNER JOIN #subject C ON B.subject_id=C.subject_id</s>
|
<s>[INST]Reversing time values into integer ones
Hi there,
Using FORMAT and DATEADD in conjunction we can get the time value as expected from a integer format.
DECLARE @iTime INTEGER = 49920
PRINT FORMAT(DATEADD(SECOND,@iTime,'00:00:00'), 'HH\:mm','es-es') + ':00.000'
What about the reverse way?
ex:
DECLARE @dTime AS TIME = '19:30:00.456'
How can we get the integer value equivalent of that?
[/INST]For integer => time you use DATEADD, so logically for time => integer you use DATEDIFF
DECLARE @dTime AS TIME = '13:52:00.000'
SELECT DATEDIFF(second, '00:00:00', @dTime)</s>
|
<s>[INST]slow performance returning resultset in sql management studio.
hello,
We have one user running a script in sql management studio , script starts returning results in 10secs however execution of query takes 30-45 mins to return complete resultset.
I run the same query on the server and it returns in 1 mins. Could this be network delay causing sql server taking time to transfer rows from server to the client? Query returns 150k rows but has lot of columns.
Any input will be appreciated.[/INST]It could certainly be a network issue. Add to this that the user's laptop may not be the fastest in the town - there is a quite a lot of work for SSMS to load that grid.
Returning 150000 rows in SSMS is way too many, and if there are many columns that just adds insult to injury.
I can't imagine that the user wants to scroll around in SSMS with the data. Figure out what the user really wants to achieve.</s>
|
<s>[INST]Help in Sql query
I am using sql compact database SDF
I need to select a column and remove all words after specific text found
for example:
Potatoes **will expire in 2022 in inventory**
when found ** remove everything
I want the output like below
Potatoes
[/INST]It seems that your post has been victim to the fact that this forum uses markdown. The double asterisks are used to indicate bold. Thus, I will need take a guess on what you had originally. Also, I don't have access to SQL Server Compact, so this is only tested on regular SQL Server:
DECLARE @text varchar(50) = 'Potatoes ** will expire in 2022 in inventory'
DECLARE @specific varchar(20) = '**'
SELECT left(@text, charindex(@specific, @text) - 1)
You can use the button with ones and zeroes to insert code (which will evade the issue with the double asterisks being gobbled up), or select piece of text to press CTRL/K to the same effect. Use the Preview button to check the result before you submit.</s>
|
<s>[INST]SqlDependency leads to strange queryplans
Hi All,
we have encountered strange issues in our database systems. In a client the message TimeOutException was found and at first we could not pinpoint the problem. After a week we found out that 3 of our 90 tables where using op to 2 minutes for doing a simple update. Selects no problem, insert no problem but updates...... It was taking ages. In the query plan of updates on each of these three tables we saw strange things happen. The query plan stated that it needed parallelism over tables that where not involved in the UPDATE table SET field=value WHERE id=id_value. The query plan showed a locking index that was not part of the system It was hanging in sys.[query_notification_*objectid*]. We could not even delete. After a loing investigation we could see that a query setup in the SqlDependency object was JOINing over 6 tables. We also found out that a windows service had no try catch block in its code and that that thread was not working anymore due to some error (of course not logged). The only way we could the database get working again was to restart the database, and restart that service again. It was a question of time before the database hung itself up again. We have changed the windows service. One change was the try catch, the other change was not using a JOIN over 6 tables anymore but only notify if a change happens in 1 table. We updated the service on production and after 3 days we see normal query plans again, no parallelism. The index created by probably the service broker was gone.
What we conclude now is that a query for SqlDependency over more than 1 table the SQL Server creates an index. That a SqlDependency object is gone leads to a database not giving an answer anymore but not cleaning up the created index until after timeout.
Does anyone have encountered the same issues when using Service Broker in SQL Server and using SqlDependency for receiving notifcations ?
[/INST]When you set up a query notification with SqlDependency, SQL Server uses the same framework as for indexed views. I don't know if it exactly creates an index, but you certainly gets ab overhead comparable to if you had created an indexed view. When you perform an update on one of the tables in the query, SQL Server needs to compute if the result actually changes.</s>
|
<s>[INST]If I add a bunch of tables in my from clause and not join but in the where I use the equal command how does this affect performace?
If I add a bunch of tables in my from clause and not join but in the where I use the equal command how does this affect performance?
For example this query section in the from clause
from OINV T0, INV1
Inner JOIN OITM ON INV1.Itemcode = OITM.ItemCode, OMRC, OCRD, OCRG T1
was this (still working on this)
from OINV T0, INV1, OITM, OMRC, OCRD, OCRG T1
[/INST]What you are describing is called "comma joins". That type of join is the same as an INNER JOIN. There is no difference.
However, you should replace those with the new style INNER JOIN.</s>
|
<s>[INST]select into use case situations
Was wondering where would I use a select into keywords as it seems to make a view or another temp like table to get data from based on my understanding.[/INST]The SELECT INTO statement creates a new table from the result set of a query. The columns of the new table inherit their names, data types, nullability, and IDENTITY property from the query’s result set.
SELECT INTO doesn’t copy constraints, indexes, or triggers from the query’s source. If you need the results in a table with the same indexes, constraints, and triggers as the source, you have to add them afterward.
Remember that the SELECT INTO statement both creates the target table (DDL) and populates it with the result set produced by the query (DML).
I often use SELECT INTO to create temporary tables for intermediate results. And sometimes use SELECT INTO to create backup copies of tables or to archive records.
For example,
SELECT * INTO Persons_backup FROM Persons
If you need a quick and dirty empty copy of some table, SELECT INTO allows you to obtain such a copy very simply. You don’t have to script the CREATE TABLE statement and change the table’s name—you just need to issue the following statement:
SELECT * INTO target_table FROM source_table WHERE 1 = 2;
Suppose you want to insert the result set of a stored procedure or a dynamic batch into a new table, but you don’t know what table structure you need to create. You can use a SELECT INTO statement, specifying OPENQUERY in the FROM clause, referring to your own server as if it were a linked server:
EXEC sp_serveroption <your_sever> , 'data access', true;
SELECT * INTO <target_table>
FROM OPENQUERY (<your_sever>, 'EXEC { <proc_name> | (<dynamic_batch>)}') AS O;</s>
|
<s>[INST]Clustering an existing SQL server 2018 instance without disruption - possible?
Is it possible to set up AlwaysOn clustering on an existing SQL server installation without a service break?
The database in question is SQL Server 2018 SP1 (AlwaysOn BAG).[/INST]If you setup the cluster role for a Windows server, then a restart is required; so no, it's not possible.
Anyway, changing an existing SQL Server into a cluster is also not possible; you have to setup Windows cluster before you install SQL Server.</s>
|
<s>[INST]Memory related
If we allocate memory for sql server then services like analysis , reporting,, integeration will consume memory from the same else we can allocate separate memory? [/INST]The memory configuration you do with `sp_configure 'max server memory'` applies only to the Database Engine. In this context, Analysis Services, Reporting Services and Integration Services are different programs just as Explorer, Word or whatever you would be running on the machine.
If you are running SSIS, SSAS and/or SSRS on the same machine, you need to account for that when you set `max server memory`-</s>
|
<s>[INST]Add column sql server
hi,
I am trying to add one column in existing table with VARCHAR(50) NULL,but it showing invalid column name .I am having dbo access for that particular database. Can you please tell me why i am not able to add that particular column.[/INST]To add a column to a table:
ALTER TABLE tbl ADD MyNewCol varchar(50) NULL
Do not use the Table Designer in SSMS! It is rotten from the inside out! Lots of bugs, and it seems that you were bitten by one of them.</s>
|
<s>[INST]Disable Foreign Key for Current Session
I know how to disable a Foreign Key.
My question is, can a foreign key be disabled for only the current session and still have it enforced for other users?
The ***simplified*** reason being, that it is a 2 column key, and I need to update some of the key columns in both tables. Cascade update would not suffice.
[/INST]That's not possible. If a foreign key is disabled, it is disabled for all sessions.
If possible, your best choice might be to do your updates during a time when no other updates are being done.
Another possibility might be to create a trigger that enforces the foreign key but code the trigger to allow foreign key violations for that particular session. Then disable the foreign key. Do your updates, re-enable the foreign key, and then drop the trigger.</s>
|
<s>[INST]SQL: Calculate data based on the date for 270 days.
Hi team - I have a requirement where i need to pull the records from the tableA based on the PostingDate. The posting date is in the int format.
For Example for today's date: 20,220,302 this is how the format is. Additional examples are for Feb 28 2022 it is in the format 20,220,228.
Now the requirement is i need to pull the data from Jan 1, 2021, to 270 days. If i run the query today, i need to get the data from Jan 1, 2021 to Sep 28 2021 ( which is 270 days from jan 1 2021). If i execute this query tomorrow i need to get the data from Jan 2 2021 to Sep 29 2021. jan 3, 2021 to sep 30 2021 etc....
Could you please help me with this calculation ?[/INST]The posting date is in the int format.
You said that the datatype of PostingDate is INT . And as Tom said, SQL Server does not add commas to numbers.Therefore you don't need to use REPLACE function.
> And I don't want to calculate going back only 425 days. Because it should calculate automatically
Do you mean :
when excute query today ,the date range is between 'DateA' and 'DateA+270days' ;
when excute on tomorrow, the date range is between 'DateA+1days' and 'DateA+271days';
when excute the day after tomorrow, the date range is between 'DateA+2days' and 'DateA+272days',and so on.
If I am right,then check this query:
SELECT * FROM YourTable
WHERE LTRIM(PostingDate) BETWEEN DATEADD(DAY, -DATEDIFF(D,'DateA','Today'), CONVERT(DATE, GETDATE()))
AND DATEADD(DAY, 270, DATEADD(DAY, -DATEDIFF(D,'DateA','Today'), CONVERT(DATE, GETDATE())));
What you need to do is to modify the two dates 'DateA' and 'Today' only once ,and then it will calculate automatically tomorrow,the day after tomorrow ......
If I assume 'Today' is March 4th,2022 and DATE A is 'Jan 1, 2021',the code will be like:
SELECT * FROM YourTable
WHERE LTRIM(PostingDate) BETWEEN DATEADD(DAY, -DATEDIFF(D,'20210101','20220304'), CONVERT(DATE, GETDATE()))
AND DATEADD(DAY, 270, DATEADD(DAY, -DATEDIFF(D,'20210101','20220304'), CONVERT(DATE, GETDATE())));</s>
|
<s>[INST]SA account keep enabled
Hello,
I have a sql server that I just rebuilt master database to change collation. For SA account, we normally renamed it and then disabled this account in my company for security purpose. After rebuilt master database, I used SA account to add more accounts, and then renamed and disabled it. But I found this account got renamed back and enabled. then I renamed and disabled it again yesterday, but it changed back again today. Does anyone knows if sql server has this behavior after master db rebuilt? :) This is first time I have this issue. anyone has any idea for this, please let me know. thank you in advance.
[/INST]There is no automated mechanism within SQL Server to disable or enable the account
If you can check the updatedate column in the sys.syslogins table to see when the login was updated.</s>
|
<s>[INST]Does not allow adding Primary key to a restored database.
Our database crashed. In the time it took us to get the data from backup client had already entered new information into the database. So we basically have data in the database that is not in the backup. I do an import for the database(backup). It errored out that due to primary keys. I stripped the keys and it allowed me to import the old data in. but now when I go to add the primary keys again I get this error:
**The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.DICOMImages' and the index name 'PK_DICOMImages'. The duplicate key value is (1.2.840.113543.6.6.4.0.6101748010736748252021090397294789472888).
Could not create constraint or index. See previous errors.
The statement has been terminated.**
I have tried removing the keys from both Source and destination databases and still I get this error. I go to the "Design" screen and there are no keys mapped there.
I need to make sure that the Primary Keys are added to the tables.
Any help would be appreciated.
ajbehzadi[/INST]Say that you want to have a Primary Key on columns (a, b, c, d). You can identify duplicate rows this way:
WITH CTE AS (
SELECT *, COUNT(*) OVER(PARTITION BY a, b, c, d) AS valuecnt
FROM tbl
)
SELECT * FROM CTE WHERE valuecnt > 1
It will be quite a mess to sort this out. It would probably have been better to keep the keys and had the two databases in parallel and try to run updates. But that would also be a lot of work depending on how much data the users have entered.
And by all means stay way from that Design screen! The Table Designer in SSMS is horribly buggy and can lead you into even deeper troubles.</s>
|
<s>[INST]all elements of index used
Hello all,
is there a way to query if theres elements in an index that don't get used?
I am aware of the e.g. dm_db_index_usage_stats.user_seeks and dm_db_index_usage_stats.user_scans to find out if an index is used at all but wonder about scenarios like this:
lets say you have an index on a customer id and later change that index to include the customer name, which gets used just fine and improves your query performance. lateron, querys change and now the query uses an index on the row id, again added the customer name as included column. other querys still use the customer id index (edited, was query), but the included customer name column is now dead weight. because its still used at all, it wont get noticed as unused index, but it could be changed to no longer include the customer name.
is there a way to query for this kind of information, if all the columns of an index are relevant?
Thanks
Florian[/INST]In theory you could query the execution plans in the plan cache or the the plans in Query Store if you have it enabled. You would have to write quite a bit of XQuery to get to the data. And it could be quite slow.
No, I am sorry, I don't have anything precooked that I can can share.</s>
|
<s>[INST]Query tuning cardinality estimation
Hi All,
We have an instance upgraded from SQL 2012 ENT to SQL 2019 ENT almost a few months back. The database is switched to the latest CE.
Now users are complaining about the performance of a few procs which seem to be performed better before migration. we do not have a benchmark in the query store to compare this.
The database is dynamic in nature and the same query returns different numbers of rows when executed continuously.
Can we use OPTION (USE HINT('QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_110')) on one query window and another without it and compare the stats? Also how do we kick off these two queries together at the same time and see the performance?
what is the best way to capture how it performed earlier and how it now?
Thanks,
ACDBA
[/INST]So the best way when you make an upgrade like this is to turn on Query Store, keep the old compat level for a week, and then bump the compat level to 150. Now you have a baseline to compare to. There is even an tool to do this in SSMS, look at the bottom at the Tasks context menu for the database. And you could still do that. That is go back and run with level 110 for a while.
But, yes, you could use that hint. I'm not sure why you would run the queries at the same time. I would just run them after each other in the same query window to compare execution times and query plans.
My experience is that when queries regresses like this there is something problematic with the query, for instance inoptimal index support. You might just have been lucky with SQL 2012. So there is all reason to see what you can do to improve the query without have to fall back on the compat level.</s>
|
<s>[INST]Plan cache
Team,
I need an query to get- SQL plan handle,sql text,plan handle,Login name,programname,database name,runningstatment and its associated batch in place, during Run time in sql server
[/INST]You can also try to use sys.dm_exec_text_query_plan, sys.dm_exec_sql_text , sys.dm_exec_requests and sys.dm_exec_sessions. Please check the query which might be helpful.
SELECT
S.login_name, S.program_name, r.session_id, t.text, q.query_plan, CONVERT(XML, q.query_plan) xml_query_plan,r.sql_handle
FROM sys.dm_exec_requests r
JOIN sys.dm_exec_sessions s
ON r.session_id = s.session_id
CROSS APPLY sys.dm_exec_text_query_plan(r.plan_handle, r.statement_start_offset, r.statement_end_offset) q
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t
WHERE
s.is_user_process = 1
AND r.session_id <> @@SPID</s>
|
<s>[INST]SQL 2014 user DB in SINGLE_USER mode ?
Hello, when a user DB is set to SINGLE_USER mode can there be any changes like running DMLs, creating/dropping/altering Tables, Stored Procs, objects, etc...?
I came across an article mentioning when in Single User mode there's no need to do DB backup on it, is this correct and why?
Thanks in advance.[/INST]when a user DB is set to SINGLE_USER mode can there be any changes like running DMLs, creating/dropping/altering Tables, Stored Procs, objects, etc...?
You bet! One reason you set the DB in single user is to deploy changes without users coming in and running queries.
> I came across an article mentioning when in Single User mode there's no need to do DB backup on it, is this correct and why?
No. Then again, you rarely keep a database in single-user for a longer time. And if you do, I guess it is not really in use. Which could imply that taking backups is not really compelling. But I would still say that the article is wrong.
Are you sure that the author was not referring to a read-only database?</s>
|
<s>[INST]How do I deploy Synchronous transactional replication? Does it require special hardware? Are there internet bandwidth need specifications for it.
Please guide as to how to deploy Synchronous transactional replication fresh. Is there any setting in SQL Server that can convert current asynchronous transaction replication to synchronous.
Also on infrastructure part; does it needs any special hardware or very high speed bandwidth; our per day load at each location is say approximately 350 entries per location per day.[/INST]Transactional replication is always asynchronous. Keep in mind that this is a quite an old feature and part of the design goal was to cover the situations where you have databases around the world, and it was not possible to have people in London to access a database in New York, because of limited network bandwidth. And even if times have changed, this is still one of the benefits of transactional replication, because it permits you to replicate data to another database with minimal impact on the source database.
If you want data to be replicated synchronous, you will need to look for a different technology. You can do this with an availability group. But an availability group sets some limits. You will need a cluster. Well, there are clusterless AGs as well, but they only support asynchronous replicas.
The reason you may implement synchronous replicas is that you want minimise downtime if a node fails, so that you get an automatic failover. But it also comes with a price: you need to wait for the log to be hardened on the replica. Normally, in an AG you have the nodes in the same data centre. You can have them on other parts of town to protect yourself against disasters like the data centre burning down. But you cannot have them cross-continent, but the maximum distance is usually give at 70-100 km. The limit is set by the maximum network speed: the speed of light.</s>
|
<s>[INST]Disable vs Dropping index in sql server?
Hi All,
If any DML operation is slow due to some index, should I disable index or drop index? If disable or drop I have to rebuild index later.
Kindly advise on differences.
Thanks
Chirag[/INST]If disable or drop I have to rebuild index later.
If you disable an index, the index definition remains and you can rebuild the index later.
If you drop the index, the definition is gone = nothing you could rebuild, you would have to re-create the index.</s>
|
<s>[INST]AG between 2 standalone instances?
Is it possible to configure AlwaysOn AG between 2 standalone instances?[/INST]starting with SQL 2017 you can set up an AG between machines that are not in a cluster by specifying CLUSTER_TYPE = NONE when you create the AG.
This kind of setup is sometimes also know as a *read-scale group*, as the main intention is give you the benefit of a readonly secondary.
In a cluster-less AG, the replicas must be asynchronous and failovers are manually. A clusterless AG cannot be considered to be an HA solution, but it certainly can serve as a DR solution.</s>
|
<s>[INST]update master table based on subtable count
Hi,
I have two table like below
create table ##tab1 (code nvarchar(50), LateFlag nvarchar(10))
create table ##tab2 (code nvarchar(50), Late nvarchar(10))
insert into ##tab1 values ('1001','')
insert into ##tab1 values ('1002','')
insert into ##tab1 values ('1003','')
insert into ##tab1 values ('1004','')
insert into ##tab2 values ('1001','N')
insert into ##tab2 values ('1001','N')
insert into ##tab2 values ('1001','Y')
insert into ##tab2 values ('1001','Y')
insert into ##tab2 values ('1002','N')
insert into ##tab2 values ('1002','N')
insert into ##tab2 values ('1002','Y')
insert into ##tab2 values ('1003','Y')
insert into ##tab2 values ('1004','N')
insert into ##tab2 values ('1004','N')
select * from ##tab1
select * from ##tab2
drop table ##tab1
drop table ##tab2
i need to update ##tab1 LateFlag column based on ##tab2 Late column count (only value as 'Y')
i need result like below
create table ##Result (code nvarchar(50), LateFlag nvarchar(10))
insert into ##Result values ('1001','2')
insert into ##Result values ('1002','1')
insert into ##Result values ('1003','1')
insert into ##Result values ('1004','0')
select * from ##Result
drop table ##Result
i tried like below
select T1.Code, ISNULL(T22.Cnt,0) from ##tab1 T1 left join
(select Code, ISNULL(COUNT(*),0) as Cnt from ##tab2 T2 where T2.code='Y'
group by code) T22 on T1.code = T22.code
Thanks
[/INST];With cte As
(Select code, Sum(Case When Late = N'Y' Then 1 Else 0 End) As LateCount
From ##tab2
Group By code)
Update t1
Set LateFlag = c.LateCount
From ##tab1 t1
Inner Join cte c On t1.code = c.code;</s>
|
<s>[INST]how to Flag
Hi everyone,
Movie table have the following attributes:
• Title
• DirectorId
• YearOfRelease
I want know how can I flag movies that are no longer available to view.
I do not want the movie removed from the table but rather that it is flagged as being unavailable.
Many thanks
[/INST]Since you don't want to add an extra column to the table,maybe you could have a try on CASE WHEN sentence,like this:
SELECT Title,DirectorId,YearOfRelease,
CASE WHEN YEAR(GETDATE())-YearOfRelease <= 2 --Modify the boolean expression here to suit your needs
THEN 'Yes'
ELSE 'No'
END AS [If Available]
FROM Movie_Table</s>
|
<s>[INST]Enterprise Evaluation Edition (180 Day Trial) and AlwaysOn Availability Groups
I just installed SQL Server 2019 Enterprise Evaluation Edition which is described as fully functional but Config Manager says AlwaysOn Availability Groups not supported.
I was looking to do some testing of AGs
Anything I am missing?
Thanks[/INST]What OS do you have?
I am not sure, but I think Config Manger is a bit misleading. What it really wants to say is that your operating system does not qualify. That is, you need a server operating system, Windows 10 or 11 won't do.
And to try all features of availability groups, you need to have a Windows Failover Cluster. But it is possible to set up an AG without a cluster, but this not really an HA solution.</s>
|
<s>[INST]Timeout occurs when accessing a SQL table
The following symptoms are occurring in SQL Server 2008.
Please tell us the cause / countermeasures.
phenomenon:
When accessing a specific table existing in SQL Server, the access times out due to the following error.
"Fatal Error: Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding. [Database Ado: Exec]"
The access frequency to the corresponding table is 00 minute every hour, and the tables are processed in the following order.
1. TRUNCATE the table
2. INSERT data into the table
environment:
SQL Server 2008 R2
supplement:
As a condition for this phenomenon to occur, when access to a table unrelated to this table occurs frequently before,
The access timeout to the table in question has occurred this time.
However, this phenomenon may occur even in such a situation. [/INST]It sounds like a blocking issue. I experienced something like this recently (SQL Server 2019). Few tables were somehow engaged in a transaction which was still running. Any selects from these tables never finished (updates, inserts resulted in some errors I don't remember which right now). So your first task would be to figure out if you have long running transactions involving these tables.</s>
|
<s>[INST]sql to combine 2 table
give 2 table
T1: list of mike tea
T2: list of topping
how to write a sql to list out all combination of mike tea and its topping?[/INST]Try this query:
_select *_</s>
|
<s>[INST]Msg 8134, Level 16, State 1, Line 1 Divide by zero error encountered.
I have below query, which is giving error of Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.
I think due to null value ,it is generating error, please guide me how to resolve it
Second thing is that, it is taking much time in executing or retrieving data
;with cte1 as(
select S.Secnam ,
ISNULL(SUM(b1.Bpqty),0)Bigbale_QTY1,ISNULL(sum(b1.Bweight),0)Bigbale_Weight1,
ISNULL(SUM(P.prdQTY),0)Smallbale_QTY1,ISNULL(SUM(case when P.prdQTY is null
then 0 else i.weight end ),0)Small_Bale_weight1
from ItemMasterFile I inner join Sections S on S.SecID=i.SecID
left outer join Probale P on P.Codeitem=I.CodeItem
LEFT OUTER JOIN Bigbalprd b1 ON i.CodeItem = b1.CodeItem
where (P.DelID is null and P.FID=1 and P.Entrydate BETWEEN @StartDate AND @Enddate or P.EntryDate is null )
and
(b1.DelID is null and b1.FID=1 and b1.EntryDate BETWEEN @StartDate AND @Enddate or b1.EntryDate is Null )
group by s.Secnam
)
,cte2 as(
select S.Secnam ,
ISNULL(SUM(b1.Bpqty),0)Bigbale_QTY2,ISNULL(sum(b1.Bweight),0)Bigbale_Weight2,
ISNULL(SUM(P.prdQTY),0)Smallbale_QTY2,ISNULL(SUM(case when P.prdQTY is null
then 0 else i.weight end ),0)Small_Bale_weight2
from ItemMasterFile I inner join Sections S on S.SecID=i.SecID
left outer join Probale P on P.Codeitem=I.CodeItem
LEFT OUTER JOIN Bigbalprd b1 ON i.CodeItem = b1.CodeItem
--where P.EntryDate='2021-10-26' and P.DelID is null and P.FID=1
where (P.DelID is null and P.FID=2 and P.Entrydate BETWEEN @StartDate AND @Enddate or P.EntryDate is null )
and
(b1.DelID is null and b1.FID=2 and b1.EntryDate BETWEEN @StartDate AND @Enddate or b1.EntryDate is Null )
group by s.Secnam
), cte1w as (
SELECT secnam,Small_Bale_weight1, Bigbale_Weight1,
( SELECT SUM(val)
FROM (VALUES (Bigbale_Weight1),
(Small_Bale_weight1 )
)AS value(val)
) as Total_Weight
FROM cte1
), cte2w as (
SELECT secnam,Small_Bale_weight2, Bigbale_Weight2,
( SELECT SUM(val)
FROM (VALUES (Bigbale_Weight2),
(Small_Bale_weight2 )
)AS value(val)
) as Total_Weight2
FROM cte2
)
select isnull(cte1w.Secnam,cte2w.Secnam) Section,cte1w.Small_Bale_weight1 Small_Bale_weight ,cte2w.Small_Bale_weight2 Small_Bale_weight1,
cte1w.Bigbale_Weight1 Bigbale_weigh,cte2w.Bigbale_Weight2 Bigbale_weigh1,Total_Weight,Total_Weight2,
sum(Total_Weight+Total_Weight2) Packed,
cast((Small_Bale_weight1)*100.0/(sum(Total_Weight)over(PARTITION BY (1) ))AS numeric(10,2))as percentagesb1 ,
cast((Small_Bale_weight2)*100.0/(sum(Total_Weight2)over(PARTITION BY (1) ))AS numeric(10,2))as percentagesb2 ,
cast((Bigbale_Weight1)*100.0/(sum(Total_Weight)over(PARTITION BY (1) ))AS numeric(10,2))as percentagebb1 ,
cast((Bigbale_Weight2)*100.0/(sum(Total_Weight2)over(PARTITION BY (1) ))AS numeric(10,2))as percentagebb2 ,
cast((Small_Bale_weight1+Small_Bale_weight2)*100.0/(sum(Total_Weight2+Total_Weight)over(PARTITION BY (1) ))AS numeric(10,2))as SBPerTotal ,
cast((Bigbale_Weight1+Bigbale_Weight2)*100.0/(sum(Total_Weight2+Total_Weight)over(PARTITION BY (1) ))AS numeric(10,2))as BBPerTotal ,
(isnull(Small_Bale_weight1,0)*100.0)/nullif(sum(Bigbale_Weight1+Small_Bale_weight1),0)as SBPer1 ,
(isnull(Small_Bale_weight2,0)*100.0)/nullif(sum(Small_Bale_weight2+Bigbale_Weight2),0)as SBPer2,
(Small_Bale_weight1+Small_Bale_weight2)*100.0/nullif(sum(Small_Bale_weight1+Small_Bale_weight2+Bigbale_Weight1),0)as SBperT
,cast((Small_Bale_weight1+Bigbale_Weight1)*100.0/(sum(Total_Weight)over(PARTITION BY (1) ))AS numeric(10,2))as Ragper1 ,
cast((Small_Bale_weight2+Bigbale_Weight2)*100.0/(sum(Total_Weight2)over(PARTITION BY (1) ))AS numeric(10,2))as Ragper2 ,
cast((Small_Bale_weight1+Bigbale_Weight1+Small_Bale_weight2+Bigbale_Weight2)*100.0/(sum(Total_Weight+Total_Weight2)over(PARTITION BY (1) ))AS numeric(10,2))as RagperTotal
from cte1w full join cte2w on cte1w.Secnam=cte2w.Secnam
group by cte1w.Secnam,cte2w.Secnam,cte1w.Small_Bale_weight1 ,cte2w.Small_Bale_weight2 ,
cte1w.Bigbale_Weight1 ,cte2w.Bigbale_Weight2 ,Total_Weight,Total_Weight2
[/INST]You need to put NULLIF function to all expressions that use /, not into only some of them. You can see, for example:
cast((Small_Bale_weight1+Small_Bale_weight2)*100.0/(sum(Total_Weight2+Total_Weight)over(PARTITION BY (1) ))AS numeric(10,2))as SBPerTotal ,
it should be changed to
cast((Small_Bale_weight1+Small_Bale_weight2)*100.0/NULLIF(sum(Total_Weight2+Total_Weight),0) over(PARTITION BY (1) ))AS numeric(10,2))as SBPerTotal ,
Also, it may help to move SUM(TotalWeight) OVER () -- no need to partition into a separate CROSS APPLY
e.g.
CROSS APPLY (select NULLIF(sum(TotalWeight),0) over() as AllTotalWeight, NULLIF(sum(TotalWeight2),0) over() as AllTotalWeight2) X and use these two expressions. Also, I haven't tested the exact syntax, it may be that you need to put NULLIF for the whole expression.</s>
|
<s>[INST]Is SQL Server Express Compatible with SBS 2011?
Can SQL Server Express 2017 be run on Small Business Server 2011? Will it work?
[/INST]as SMS 2011 is based on Windows 2008 R2... the answer is "NO".
Technically it might work BUT it is not supported and maybe setup will tell you it is not a supported OS.
If this answer helps you, please mark it as helpful/answered,</s>
|
<s>[INST]Tempdb adding new data files
Tempdb is currently having 8 data files. If I added 4 new data files and then restart sql server, will tempdb get recreated with 12 data files?[/INST]\> If I added 4 new data files and then restart sql server, will tempdb get recreated with 12 data files?
**The answer is Yes**, the tempdb will have 12 data files after you added 4 new data files. And you do not need to restart the SQL server to make this change effect.
A very popular question is how many Temp data files should one have it. **The number of secondary data files depends on the number of (logical) processors on the machine.** As a general rule, if the number of logical processors is less than or equal to eight, use the same number of data files as logical processors. If the number of logical processors is greater than eight, use eight data files. Then if contention continues, increase the number of data files by multiples of four until the contention decreases to acceptable levels, or make changes to the workload/code. Refer to MS document.
In addition, you can use below T-SQL to check the files of SQL server database.
SELECT
name 'Logical Name', type_desc,
physical_name 'File Location'</s>
|
<s>[INST]Service broker and bad plans - any way (besides reboot) to correct it if FREEPROCCACHE doesn't?
We have a Service Broker activated stored procedure that's constantly running on 30 spids on a sql server 2012 server (yes, I know, we're migrating it next month). Every once in a while (like, it happened last week, but not in the past 9 months) it gets a bad plan and can't process fast enough. The stored procedure is a combination of SQL and a CLR. Doing a checkpoint/DROPCLEANBUFFERS/freeproccache doesn't seem to fix it, even run multiple times, but a reboot almost always does.
Is there any reason why that doesn't fix it? Is there any way TO fix it? Thanks.[/INST]It is impossible to answer the question with the information you have shared. You need to track down what is the slow statement. And for that matter, you need to investigate if there is some blocking.
If you don't know what is slow and why it is slow, you cannot fix it confidence. DBCC FREEPROCCACHE and things like that are just shots in the dark.
Maybe you should wait until you have a newer version of SQL Server installed. Not the least because then you can activate Query Store which will help you track down slow queries a lot more easily.
Query Store is also good to catch regressions that may occur when you move to a higher compatibility level. So a possible strategy is:
1. Install the new version of SQL Server. Keep the compat level.
2. Enable Query Store.
3. Run for a week or two.
4. Change the compat level to the new one.
5. If a query regresses, you can find it with help of Query Store.
There is even an option for this in SSMS, you find it at the bottom of the Tasks context menu for a database.</s>
|
<s>[INST]Is a mistake to use port 1443 for an SQL Server instead of the default port1433.
Hi! I would like to ask if it is a mistake to use port 1443 for an SQL Server instead of the default port1433?
I use 1443 port in my script, so is it worth it to change it ? and why ?[/INST]You can use 1443, but technically 1443 is a reserved port for another purpose. You may run into issues in the long run. You are better off using >10,000 to avoid any predefined ports.</s>
|
<s>[INST]sql server backup permision server wide role
Hi,
Is it possible to create a server role with backup permission on all DBs?
I understand the possibility of a db_backupoperator or db_owner for every single database, but server wide?
Thanks Alen[/INST]Quoting Books Online:
> BACKUP DATABASE and BACKUP LOG permissions default to members of the sysadmin fixed server role and the db_owner and db_backupoperator fixed database roles.
Which is a bit of a pity, as you may have a junior DBA that should be able run backups without being sysadmin.
What you can do is to write a stored procedure that runs the backup commands needed, and where you check the input parameters. Then you sign that procedure with a certificate from which you create a login that you add as member to sysadmin. Finally, you grant permission on this procedure to the junior DBA.</s>
|
<s>[INST]LAG & LEAD depending on other column
Hi there,
DECLARE @tMovements AS TABLE(id2 INT, typeop CHAR(1), amount DECIMAL(18,2), createdate DATE)
INSERT INTO @tMovements(id2,typeop,amount,createdate)
select 1, 'D',2500,'2022-01-01'
UNION
SELECT 2,'D',3456.25,'2022-01-01'
UNION
SELECT 3,'C',-5250,'2022-01-01'
UNION
SELECT 4, 'C',-3000,'2022-01-05'
UNION
SELECT 5,'D',10000,'2022-01-06'
UNION
SELECT 6,'C',-1500,'2022-01-31'
select * from @tMovements
I'd need to get the good ledger according to whether credit or debit and get the good ledger
desired outcome
id2 amount createddate
2 5956.25 2022-01-01
3 706.25 2022-01-01
4 -2293.75 2022-01-05
5 7706.25 2022-01-06
6 6206.25 2022-01-31
Thanks a lot,
[/INST]Please try the following solution.
**SQL**
-- DDL and sample data population, start
DECLARE @tMovements AS TABLE(id2 INT, typeop CHAR(1), amount DECIMAL(18,2), createdate DATE);
INSERT INTO @tMovements(id2,typeop,amount,createdate) VALUES
(1, 'D',2500,'2022-01-01'),
(2,'D',3456.25,'2022-01-01'),
(3,'C',-5250,'2022-01-01'),
(4, 'C',-3000,'2022-01-05'),
(5,'D',10000,'2022-01-06'),
(6,'C',-1500,'2022-01-31');
-- DDL and sample data population, end
SELECT *
, result = SUM(amount) OVER (ORDER BY id2)
FROM @tMovements;
**Output**
| id2 | typeop | amount | createdate | result |
| 1 | D | 2500.00 | 2022-01-01 | 2500.00 |
| 2 | D | 3456.25 | 2022-01-01 | 5956.25 |
| 3 | C | -5250.00 | 2022-01-01 | 706.25 |
| 4 | C | -3000.00 | 2022-01-05 | -2293.75 |
| 5 | D | 10000.00 | 2022-01-06 | 7706.25 |
| 6 | C | -1500.00 | 2022-01-31 | 6206.25 |</s>
|
<s>[INST]How to Enter NULL
In Sql server2016,I was pasting data into a table, how do i enter 'null' into a cell?
I try to some ways to get it, but failed.Hope to get support........[/INST]Hi,newbie
If I understand correctly, if you want to insert null on the empty column, you can try 2 ways.
A simple method is to add '' directly. SQL will treat it as a string, or you can use Ctrl + 0 to implement it.</s>
|
<s>[INST]How to Turn this SQL Pivot Procedure into a SQL Pivot View
I have an existing PIVOT table that is generated from a stored procedure that I'm wondering if I can get some help with turning this into a PIVOT table in a standard query view in SQL Server (Express), if possible.
I have no problem with the stored procedure working properly for my situation. This procedure was created a while back from a source I found at that time, and I'm not knowledgeable enough to build something like this all on my own in SQL Server just yet. I'm mostly trying to understand better how to do PIVOT tables in a view since I may have to do this more than a few times with this data because of how it is stored in the database. I'm not sure what other information would be needed, so please ask.
USE [Part Class]
GO
/****** Object: StoredProcedure [dbo].[sp_CategoryPartAttributeValue] Script Date: 4/15/2022 4:24:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Don Petry
-- Create date: 7/11/21
-- Description: Returns pivoted category and attribute data
-- =============================================
ALTER PROCEDURE [dbo].[sp_CategoryPartAttributeValue]
-- Add the parameters for the stored procedure here
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SET FMTONLY OFF;
-- Insert statements for procedure here
DECLARE
@columns NVARCHAR(MAX) = '',
@sql NVARCHAR(MAX) = '';
-- select the category names
SELECT
@columns += QUOTENAME(AttributeDesc) + ','
FROM
dbo.Attribute
ORDER BY
AttributeDesc;
-- remove the last comma
SET @columns = LEFT(@columns, LEN(@columns) - 1);
-- construct dynamic SQL
SET @sql ='
SELECT * FROM
(
SELECT dbo.Category.CategoryID,
dbo.Category.CategoryDesc,
dbo.PartNumbers.PartID,
dbo.PartNumbers.PartNumber,
dbo.PartNumbers.Description,
dbo.PartNumbers.PartStatus,
dbo.PartNumbers.OrderType,
dbo.PartNumbers.PrevPN,
dbo.PartNumbers.BOSS_OH_QTY,
dbo.Attribute.AttributeDesc,
dbo.PartAttribute.PartAttributeValue
FROM dbo.PartNumbers
INNER JOIN dbo.PartAttribute ON dbo.PartNumbers.PartID = dbo.PartAttribute.PartID
INNER JOIN dbo.Attribute ON dbo.PartAttribute.AttributeID = dbo.Attribute.AttributeID
INNER JOIN dbo.PartCategory ON dbo.PartNumbers.PartID = dbo.PartCategory.PartID
INNER JOIN dbo.Category ON dbo.PartCategory.CategoryID = dbo.Category.CategoryID
) PN
PIVOT (
MAX(PartAttributeValue)
FOR AttributeDesc IN ('+ @columns +')
) AS PVT;';
-- execute the dynamic SQL
EXECUTE sp_executesql @sql;
END
[/INST]You can't make a view out of that. A view is just like a table: it has a constant set of columns with well-defined names. You procedure seems to be running a dynamic pivot - which is a non-relational operation - which can produce a different number of columns with different names each time.
It is possible to write static pivot queries, but then you will need to accept static names for your columns and a static number of columns.</s>
|
<s>[INST]stored procedure returing a string for a C# app
Hello all;
I have the following stored procedure below
> create procedure dbo.test_sp (@p_para varchar(10) out)
> as
> begin
> set @p_para = select 'this is a test'
> return @p_para
>
> c# code below
>
> using (Sqlconnection conn = new SqlConnection(getconnectionstring()))
> using (Sqlcommand cmd = conn.CreateCommand())
> {
>
> cmd.CommandText = "dbo.test_sp";
> cmd.CommandType = CommandType.StoredProcedure;
> cmd.Parameters.Add(@p_para, SqlDBType.String);
>
> SqlParameter retval = new SqlParameter(@Returnval, System.Data.SqlDbType.String);
> retval.Direction = System.Data.ParameterDirection.ReturnValue;
> cmd.Paramters.Add(retval);
> conn.Open();
>
> cmd.ExecuteNonQuery();
> string str_retval = retval.value.ToString();
>
> }
However, I noticed, it doesn't return anything in my str_retval when I run my application and I don't know why. Thanks in advanced.
[/INST]Try this C# code:
using (Sqlconnection conn = new SqlConnection(getconnectionstring()))
using (Sqlcommand cmd = conn.CreateCommand())
{
cmd.CommandText = "dbo.test_sp";
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter para = cmd.Parameters.Add("@p_para", SqlDbType.String, 10);
para.Direction = ParameterDirection.Output;
conn.Open();
cmd.ExecuteScalar();
string str_retval = (String)para.Value;
// . . .</s>
|
<s>[INST]SQL Server 2019 Standard Standalone Installation
Hello folks,
We have an offline machine which is not possible to connect to the internet. I need to install SQL Server 2019 Standard on this machine, but all I can find is web installations that need an online connection.
Is there a way to install it without a connection to the internet?
Kind regards,
Daniel[/INST]Yes. Do the download on one machine. Start the download. Select "Download Media" to get the ISO. Then bring the ISO to the offline machine.
If you want to add any of the Machine Learning components there are some extra steps that you need to take. (That I don't recall the details of on the top of my head.)</s>
|
<s>[INST]select SERVERPROPERTY('MachineName') CASE sensitive
in SQL 2019, select SERVERPROPERTY('MachineName') returned lower case.
in SQL 2008, returned upper case.
dos command hostname returned lower case on both server.
select @@servername returned upper case on both.
Any idea why SQL 2019 SERVERPROPERTY returned lower case? Any change on SERVERPROPERTY?
Thanks,
Sky[/INST]Windows server names are not case sensitive. However, Linux names can be. So this may have been a change to address multiple platforms.
It should not affect anything either way.</s>
|
<s>[INST]SqlServer dynamic data masking per selected row
Can Sql Server Dynamic Data Masking be applied on specific rows?
Ex. based on a date column value falling within a range, another column in that row will be (or not) masked?
If not, what are the other options?
I'm sure this has been addressed before, but i can't find any info on this.
thanks
[/INST]that is not possible. This is something you would need to implement yourself.
Overall, Dynamic Data Masking is basically an application helper; it is not really a security feature.</s>
|
<s>[INST]For a linked server to Oracle using LDAP authentication, if the ldap.ora and/or sqlnet.ora files used by the SQL server are modified does the SQL Server need to be restarted?
For a linked server to Oracle using LDAP authentication, if the ldap.ora and/or sqlnet.ora files used by the SQL server are modified does the SQL Server need to be restarted? We need to change the Oracle OID becuase of a corporate reorg and therefore need to update the ldap.ora file. We have seen inconsistent results in testing this in Dev/QA/UAT environments and want to know if it is a requirement that we restart the SQL Server[/INST]I assume that you are using Oracle's OLE DB provider for the linked server. To get an authoritative answer, you would have to ask Oracle. SQL Server as such does not know how Oracle's OLE DB provider behaves.
You say that you get inconsistent results. My interpretation is that sometimes you have tested, you have been able to change the file without having to restart SQL Server, sometimes not. I would take this that sometimes the provider reads the file, but not on every connection, but it may cache data.
Thus, if you don't want to rely on chance, you need to restart SQL Server.
Please note that I have no experience of working with Oracle at all, nor directly, nor through linked server. I'm just speculating from my experience of how stuff works in general.</s>
|
<s>[INST]which is best truncate or delete to remove all rows from table student_course?
I work on sql server 2017
i need to delete all rows from table student_course
but i don't know use
delete from student_course
or
truncate table student_course
table student_course
studentid pk
courseid pk
table student table
studentid pk
table courses
courseid pk
---------------------------------------------
student_course table have relation with courses table and student table
so which command will be used to delete all rows from table student_course
truncate or delete ?
What I have tried:
delete from student_course
or
truncate table student_course[/INST]If you want to delete all rows from student_course and there are no dependencies on that table in the database, the TRUNCATE TABLE student_course should be faster.</s>
|
<s>[INST]SQL server audit logs filtering is not working
Hello,
I'm using SQL server management studio 18.11.1.
I've enabled the audit.
When I open the audit logs, I can see entries.
But when I try to filter based on dates or user or ... nothing is displayed.
Any idea?
Best regards.
Marc[/INST]You can also use T-SQL to view the Audit Log. you can filter by adding a where statement after the statement below.
SELECT * FROM sys.fn_get_audit_file('F:\AuditTest\*.sqlaudit', DEFAULT, DEFAULT)
To check if it is the problem of SSMS version, I also installed the latest version of SSMS, but my filter still works.
After executing the statement if there are any errors you can post it.</s>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.