text
stringlengths 209
10.7k
|
---|
<s>[INST]Hello- I want to search the Expcode of 'ST' for Maintree-'RD' only. I want to see all Expcode which is mapped related with 'ST'. If you see ExpCode-ST, it is mapped with 'DT'
if you see ExpCode-DT is mapped with 'DN'
if you see ExpCode-DN is mapped with 'DD'
Create table ERT (MainTree char(10), ExpCode char(4), MapCode char(4), Edate datetime)
Insert into ERT values ('RD','ST','DT','2020-01-01')
Insert into ERT values ('RD','DT','DN','2020-01-01')
Insert into ERT values ('RD','DN','DD','2020-01-01')
Insert into ERT values ('RD','DD', NULL,'2020-01-01')
So I want to see the following result from query -
Criteria - I want to see all Expcode which is mapped/related with Expcode-'ST'. Bascially I want to see all tree of Expcode-ST.
Maintree ExpCode MapCode Edate
RD DD NULL 2020-01-01
RD DT DN 2020-01-01
RD DN DD 2020-01-01
RD ST DT 2020-01-01
[/INST]](/users/na/?userid=d1f1d8c9-54cf-46d9-8589-f92ad4176860)
If I understand correctly, what you need is a recursive query.
```
;with CTE as(
select * from ERT where ExpCode = 'ST'
union all
select A.* from ERT as A inner join CTE as B
on A.ExpCode = B.MapCode)
select * from CTE;
```
Since there is something in your description that confuses me, I'm not sure if this is what you want, and if that's not what you want, please comment.</s>
|
<s>[INST]Hello,
I have multiples tables and I need to partition them using partition function and partition scheme.
Can i use the same partition function and scheme for all the tables that i want to partition?????
the partition is on daily basis for all tables.
I need to know also if there is any impact in using same partition function and scheme in future regarding management and performance ??
Thanks,
Bassam Geagea
[/INST]You can do use the same partition function/scheme for multiple tables. One advantage is you only need to change one partition function and not many. But the day you want to do SPLIT/MERGE RANGE in a way that it leads to data movement, you may get second thoughts....</s>
|
<s>[INST]I am trying to uninstall SQL Server 2019 express
[/INST]](/users/na/?userid=64ab7d8e-34c7-4615-9df5-a49525823cc6),
Do you have any error messages to report. If so, you can post it. In order to solve your problem more efficiently, you need to add more details to your problem.
Also, here is a step by step to uninstall a clean SQL Server. I'll put it here first.
Please follow the below steps to remove all components of previous installed SQL Server completely:
1. Remove all SQL Server components from 'Programs and Features'
2. Backup the registry
3. Delete the following keys in regedit:
--HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server
--HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer
4. Go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall and delete all the sub-keys referencing SQL Server
5. Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services and delete all the keys referencing SQL Server
6. Reboot the machine
If you want to install it again, please use an administrator account to reinstall SQL Server on your computer(Right click->run as administrator).</s>
|
<s>[INST]I have a spatial table that I imported from ArcGIS file geodatabase into SQL Server. In the table, there are hundreds of duplicate rows having the same ID that I need to "merge"/combine into a single row (which would result in combining two polygons into one for each polygon having the same ID--usually two).
Does anyone know how this can be done? I can manually merge them using ArcGIS Pro but there are thousands of these rows that it's impossible to complete this task in due time.
Appreciate any help.[/INST]It seems like there's nobody to answer my question. So I went back to ArcGIS Pro. I used the tool, "Dissolve" (I forgot about this tool). I specified the dissolved field as the ID of the feature. The tool then dissolves all features into one if the value of the ID is the same.
This in effect got rid of the duplicate data. I can then export the resulting feature class or table into SQL Server for further queries using other tables I need.</s>
|
<s>[INST]Hi Everyone,
we have 3 SQL 2012 servers in different versions 11.06.6020, 11.0.7001.0 and 11.0.5058.0. Our secure team want us upgrade to SP4, I am new to this, I see there is KB5021123 Sp4 GDR security update released back in Feb 14 2023, can I just install KB5021123 or do I need to upgrade one at a time and work my way up?
Any help is much appreciated.
Thanks
Tim
[/INST]](https://learn.microsoft.com/en-us/users/na/?userid=cb6f7b4b-76dc-4db3-b85f-a53fcedab547),
You do not need to install the previous Service Packs before installing SQL Server 2012 Service Pack 4 (SP4). SQL Server 2012 SP4 contains all the updates from the previous Service Packs.
Also, let me add the difference between GDR and CU.
GDR (General Distribution Release) is a security update release of SQL Server that focuses on patching known security vulnerabilities and bugs.GDR does not include any new features or fix known non-security issues, but rather focuses on patching and fixing known security vulnerabilities.GDR usually does not change existing features and feature behavior.
CU (Cumulative Update) is a feature update version of SQL Server that is primarily used to include new features, performance optimizations, and bug fixes. CU includes not only patches for known security vulnerabilities, but also fixes other bugs and improves performance. cU may also change existing features and feature behavior, and therefore requires more thorough testing.
Therefore, if your SQL Server has security vulnerabilities, you should first install GDR. if you need more feature updates and bug fixes, you should install the latest CU.</s>
|
<s>[INST]Hi All,
Is there any query using which we can tell what is the table which is changing the most or more frequently? The idea, is to identify those tables and run update statistics with full scan on daily basis instead of weekly basis.
Regards,
Sam
[/INST]In SQL Server, you can use the **sys.dm_db_index_usage_stats** dynamic management view to gather information about index usage and changes. This can help you identify tables with frequent updates, inserts, and deletes. Please note that these statistics are reset when the SQL Server instance is restarted.
sql
SELECT
OBJECT_NAME(ius.object_id) AS TableName,
SUM(ius.user_updates) AS TotalUpdates,
SUM(ius.user_seeks + ius.user_scans + ius.user_lookups) AS TotalReads
FROM
sys.dm_db_index_usage_stats ius
JOIN
sys.indexes idx ON ius.object_id = idx.object_id AND ius.index_id = idx.index_id
WHERE
ius.database_id = DB_ID() -- Current database
AND idx.type_desc <> 'HEAP'
GROUP BY
ius.object_id
ORDER BY
TotalUpdates DESC;</s>
|
<s>[INST]求助,我要在电脑上使用TD-GIS专业软件,其中有一项功能需要shapelib.dll模块,需要安装sql2005 standard edition。
但是安装时提示 SQL Server 安装程序意外失败,请问可能是什么原因?
我的系统是Windows 7 旗舰版 service pack 1 64位
安装的是SQL Server 2005 standard edition
Windows功能打开了 indexing service,internet explorer 9,internet information services 可承载的Web核心,internet信息服务,Microsoft .net framework 3.5.1,microsoft message queue(MSMQ)服务器。
报错的信息如下:
Summary
Microsoft SQL Server 2005 9.00.1399.06
==============================
OS Version : Professional Service Pack 1 (Build 7601)
Time : Sat Apr 15 22:48:04 2023
SQLSetup0018_ZJZL-20211227OK_Core
```
Microsoft SQL Server 2005 Setup beginning at Sat Apr 15 22:34:33 2023
Process ID : 5004
C:\Users\Administrator\Desktop\sql_2005_standard_64\cs_sql_2005_std_x64_cd1\setup.exe Version: 2005.90.1399.0
Running: LoadResourcesAction at: 2023/3/15 22:34:33
Complete: LoadResourcesAction at: 2023/3/15 22:34:33, returned true
Running: ParseBootstrapOptionsAction at: 2023/3/15 22:34:33
Loaded DLL:C:\Users\Administrator\Desktop\sql_2005_standard_64\cs_sql_2005_std_x64_cd1\xmlrw.dll Version:2.0.3604.0
Complete: ParseBootstrapOptionsAction at: 2023/3/15 22:34:33, returned false
Error: Action "ParseBootstrapOptionsAction" failed during execution. Error information reported during run:
Could not parse command line due to datastore exception.
Source File Name: utillib\persisthelpers.cpp
Compiler Timestamp: Fri Jul 29 01:13:55 2005
Function Name: writeEncryptedString
Source Line Number: 124
----------------------------------------------------------
writeEncryptedString() failed
Source File Name: utillib\persisthelpers.cpp
Compiler Timestamp: Fri Jul 29 01:13:55 2005
Function Name: writeEncryptedString
Source Line Number: 123
----------------------------------------------------------
Error Code: 0x80070005 (5)
Windows Error Text: Error: Action "ActivateLoggingAction" threw an exception during execution. Error information reported during run:
Datastore exception while trying to write logging properties.
Source File Name: datastore\cachedpropertycollection.cpp
Compiler Timestamp: Fri Jul 29 01:13:49 2005
Function Name: CachedPropertyCollection::findProperty
Source Line Number: 130
----------------------------------------------------------
Failed to find property "primaryLogFiles" {"SetupStateScope", "", ""} in cache
Source File Name: datastore\propertycollection.cpp
Compiler Timestamp: Fri Jul 29 01:13:50 2005
Function Name: SetupStateScope.primaryLogFiles
Source Line Number: 44
----------------------------------------------------------
No collector registered for scope: "SetupStateScope"
00000000046AAF70Unable to proceed with setup, there was a command line parsing error. : 2
Error Code: 0x80070002 (2)
Windows Error Text:
Class not registered.
Failed to create CAB file due to datastore exception
Source File Name: datastore\cachedpropertycollection.cpp
Compiler Timestamp: Fri Jul 29 01:13:49 2005
Function Name: CachedPropertyCollection::findProperty
Source Line Number: 130
----------------------------------------------------------
Failed to find property "HostSetup" {"SetupBootstrapOptionsScope", "", "5004"} in cache
Source File Name: datastore\propertycollection.cpp
Compiler Timestamp: Fri Jul 29 01:13:50 2005
Function Name: SetupBootstrapOptionsScope.HostSetup
Source Line Number: 44
----------------------------------------------------------
No collector registered for scope: "SetupBootstrapOptionsScope"
Message pump returning: 2
```
[/INST]microsoft.com/en-us/users/na/?userid=55a73cda-5de0-48f8-829e-c1376e6ca1ac),
问题似乎是安装程序缺少源文件。如果您从 CD/DVD 复制安装文件,则有两个文件夹,Servers 和 Tools。这两个文件夹必须在同级文件夹或驱动器的根文件夹下。这些文件夹的名称必须完全是 Servers 和 Tools。Servers 文件夹包含安装主要 SQL Server 2005 组件(如数据库引擎)所需的所有文件。Tools 文件夹包含 SQL Server 2005 的工具组件和联机丛书。
另外,SQL Server2005版本太老了,已经超出了产品支持得周期,建议你可以下载使用更新的版本。</s>
|
<s>[INST]Hello, I need some help with SQL.
I have a table that contains three columns A, B, and C. I need to group according to columns A and B, and then sort according to column C to get the top two records of each group. I cannot figure out how to do it. I appreciate any help.
[/INST]microsoft.com/en-us/users/na/?userid=9ed3a9df-d674-460c-95d7-61838e5ae853)
You only need one analytical ranking function. You can try this query.
```sql
;with CTE as(
select A,B,C,row_number()over(partition by A,B order by C) as num from table)
select * from CTE where num < 3;
```
If you still have problems, you can provide your source data and the results you expect to output.</s>
|
<s>[INST]Hello,
I have an Always On Cluster in SQL Server 2019 (15.0.4298.1) and my security officer tell me that the "SQL server 2012 native client driver" must be uninstall because it's not supported since July 2022.
Can I uninstall it without harming the cluster ?
Most recent drivers are installed :
- Microsoft ODBC Driver 17
- Microsoft OLE DB Driver
Thanks for your help.
[/INST]I can't say for sure, but I find that I have a machine with SQL 2019 that has this driver, and I have not made much else on this machine, so I would assume that the driver came with SQL 2019. Which still is supported.
Why it ships and if it is needed, and if something would break if you uninstall it, I don't know. But I would have a further discussion with the security officer, if I were you.</s>
|
<s>[INST]HI team
i have two date fields one is date,Invoicedate
Date,Invoicedate
Date InvoiceDate
2022-11-20 16:34:00 2021-11-30 00:00:00
2022-07-14 16:34:00 2022-07-14 00:00:00
2022-10-07 16:34:00 2021-10-07 00:00:00
From the above date field
i would like to update the date value to the end of the month date, as like below date given for example.
Date Invoice Date
2022-11-30 00:00:00 2021-11-30 00:00:00
2022-07-31 00:00:00 2022-07-14 00:00:00
2022-10-31 00:00:00 2021-10-07 00:00:00
How do i update please give me the query to get this these dates
Thank you!
[/INST]sql
DECLARE @dt DATETIME = '2022-10-07 16:34:00'
SELECT @dt AS CurrentDate, CAST(EOMONTH(@dt) AS DATETIME) AS InvoiceDate</s>
|
<s>[INST]Hi, the comma after 'STU_A' gives me an error but I don't understand why. Can anyone help?
SELECT
BookRef,
SourceSiteId,
BookingStatus AS Status,
RoomTypeCode AS Decsription,
MarketSegment AS MARKSEG,
DateArrive,
DateDepart,
PackageCode,
DATENAME(month, DateArrive) AS Month,
Year(DateArrive) ArrivalYear,
ChargeTotalNett AS TOTALAccomREV
FROM SyncReservations
WHERE (CreatedTimestamp \< '2020-08-01' AND DateArrive BETWEEN '2020-09-01' AND '2022-07-31')
or (PackageCode NOT LIKE
'STU_A' ,
'STU_B',
'STU_C',
'STU_D' ,
'STU_A\_2' ,
'STU_B\_2',
'STU_C\_2'
)
Order BY MarketSegment
[/INST]What did you change?</s>
|
<s>[INST]To perform some testing, I ran the following:
USE mydb;
GO
EXEC sp_configure 'show advanced options', 1;
GO
RECONFIGURE ;
GO
EXEC sp_configure 'user connections', 1;
GO
RECONFIGURE;
GO
Then I restarted the computer.
Then I am unable to connect to the SQL Express Server.
Then I installed SQL Developer Server. Changing port numbers is a small price to pay for being able to continue working.
While I can now use the server, I am unable to do any development because when my application tries to connect, it gets "Error reading prelogin response: Connection reset".
So, I try to open SQL Server 2019 Configuration Manager, and it gives the error prompt "Cannot connect to WMI provider. You do not have permission or the server is unreachable. Note that you can only manage SQL Server 2005 and later servers with SQL Server Configuration Manager. Invalid class [0x80041010]"
And when I try to uninstall, repair, or whatever, I get "Registry_SOFTWARE_Wow6432Node_Microsoft_MSSQLServer.reg_ Slp: Value cannot be null."
How to resolve? If it's too screwed, then how to manually remove everything so that I can install a fresh copy?[/INST]backup mdf and ldf. then just delete EVERYTHING - all SQL Server dirs, and remove \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server
MS errors are so ridiculously non-helpful.</s>
|
<s>[INST]Hi
I have a question for license rules regarding MS SQL CAL licenses, let me describe:
If have different installation of MS SQL server Standard installed on different servers internally, and it is the same users that are accessing these different SQL servers, do each user need to have a CAL license for each installation or is one CAL per. user enough?
Thanks in advance :-)
[/INST]This is no legal advice! You must ask a Microsoft representative if you want an official Microsoft statement.
For questions regarding pricing/licensing, please get in touch with a Microsoft sales partner or licensing expert.
Call (1-800-426-9400), Monday through Friday, 6:00 AM to 6:00 PM PST, to speak directly to a Microsoft licensing specialist.
My personal opinion on your question:
According to the SQL Server 2019 license guide, you just need a server license for each SQL Server and additionally one (!) CAL license for each accessing user... doesn't matter which SQL Server that person is connecting to.
> Each SQL Server CAL allows access to multiple licensed SQL Servers, including Standard Edition and legacy Business Intelligence and Enterprise Edition Servers.
I hope my answer is helpful to you,
Your</s>
|
<s>[INST]Is it possible to integrate Cumulative Updates into the SQL Server Express 2016 installation? We are currently patching the product with Config Manager, but would like to get the installation that runs through OS deployment patched during the installation task sequence, rather than having to manually update, or wait for software updates to be applied post install. [/INST]Ended up modifying my configuration ini file to Updates = True and setting the Update Source as suggested to the Updates folder in my installation source. Worked perfectly.</s>
|
<s>[INST] Hello, I've been researching around the web and still a bit confused difference between ADMINISTER BULK OPERATIONS vs bulkadmin.
From a security perspective...which is better for least privilege to allow Bulk Insert only just for their one DB that they are in db_owner role ?
Thanks in advance.[/INST]](/users/na/?userid=c3f24d5f-ee40-4f97-b236-ea903a9529a5),
ADMINISTER BULK OPERATIONS is a more granular permission than "bulkadmin" and allows more control over who can perform bulk operations.
ADMINISTER BULK OPERATIONS allows users to perform both import and export operations while "bulkadmin" only allows import operations.
In detail, the ADMINISTER BULK OPERATIONS role grants permissions to execute the BULK INSERT statement, as well as to execute the bcp utility and the OPENROWSET(BULK...) function. This role also grants permissions to read from and write to external files, and to specify format files. In contrast, the bulkadmin role grants permissions to execute the BULK INSERT statement and the bcp utility, but does not provide as much flexibility for configuring these operations.
To allow a user to perform bulk insert operations for their own database only, you could add them to the db_owner role for that database, and then grant them the ADMINISTER BULK OPERATIONS role at the server level. This will allow them to perform bulk insert operations for their own database, but not for other databases on the server. This approach provides a more granular level of security compared to granting the bulkadmin role, which would give the user access to perform bulk insert operations on all databases on the server.
It is recommended to use "ADMINISTER BULK OPERATIONS" instead of "bulkadmin" as it provides more control and is less powerful, limiting the scope of what a user can do.</s>
|
<s>[INST]Suppose I have table with columns: ID, Group Number, Value. Want the SP code output the Max value of specific Group Number and then use this max value in further query.
Tried this:
```
CREATE PROC SP_TestOutput
@GroupNum int,
@max_value int Output
AS
Select @max_value = MAX(val)
From mytable
Where GroupNum = @GroupNum
EXEC SP_TestOutput @GroupNum=1001
Select ID
From mytable Where Col2 = @max_value
```
Please help, thanks in advance.
[/INST]microsoft.com/en-us/users/na/?userid=772119a2-1f56-46b7-abb1-4ad3b69358cc)
You need another parameter to receive the output value in the Execute clause.
Try this:
```
EXEC SP_TestOutput @GroupNum=1001 , @max_value=@max_value_final OUTPUT
Select ID
From mytable Where Col2 = @max_value_final
```</s>
|
<s>[INST]We just migrated our SCCM database to new SQL servers (remote system, configured as an Always On Availability Group).
For the most part everything has gone smoothly, however in the component logs for the SMS_REST_PROVIDER I'm getting the error "Administration service process failed to create a database connection." constantly.
For readability, I'm putting the error message I'm seeing in the AdminService.log in the bottom of this thread. I already know the server hosting the Administration Service has permissions to connect to SQL, and all the other servers and services seem to be connecting just fine.
I don't see anywhere that specifies which SQL server it's trying to connect to. So I'm wondering if the Administration Service didn't update it's connection string to the new servers with everything else, but I can't find a way to validate or update it.
We don't use the Administration Service yet, however it is in our plans to switch to this soon for console connections, so I'm trying to get this sorted out.
----------
AdminService.log error:
Exception during request processing.
System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - The wait operation timed out.) ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at Microsoft.ConfigurationManager.AdminService.Data.SCCMDataSql..ctor(IList`1 allEntityTypes, IServiceConfig serviceConfig, ILogger logger)
at Microsoft.ConfigurationManager.AdminService.DbContextMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.ConfigurationManager.AdminService.RequestLoggingMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.ConfigurationManager.AdminService.ThrottlingMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Host.HttpListener.OwinHttpListener.<ProcessRequestAsync>d__5.MoveNext()
ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:258,State:0,Class:20
[/INST]This turned out to be a generic network communications issue with the SQL server. We had a firewall rule blocking incoming SQL connections (1433) from that server to our new SQL servers.
I thought that the logs had shown this working previously but I was mistaken. Once we opened that port all of the errors for this server were resolved.</s>
|
<s>[INST]Dear all,
I would need to apply two conditions on the same WHERE clause using EXIST.
XML excerpt
```
Jobs>
<Job JobName="Formulatrix Database Index Rebuilding.Subplan_1" JobEnabled="true" ScheduleName="Formulatrix Database Index Rebuilding.Subplan_1" ScheduleFrequency="Weekly" ScheduleInterval="Sat " ScheduleTime="01:00:00" ScheduleTimeDescription="Starting at 01:00:00" NextRunTime="2023-05-13 01:00:00" LastRunStatus="Successful" />
<Job JobName="Integrity_check_DBCC" JobEnabled="true" ScheduleName="monthly_integrity_check_schedule_wave2" ScheduleFrequency="Every 1 Months" ScheduleInterval="First Sat" ScheduleTime="20:00:00" ScheduleTimeDescription="Starting at 20:00:00" NextRunTime="2023-06-03 20:00:00" LastRunStatus="Successful" />
<Job JobName="syspolicy_purge_history" JobEnabled="true" ScheduleName="syspolicy_purge_history_schedule" ScheduleFrequency="Daily" ScheduleInterval="Every Day" ScheduleTime="02:00:00" ScheduleTimeDescription="Starting at 02:00:00" NextRunTime="2023-05-09 02:00:00" LastRunStatus="Successful" />
</Jobs>
```
This query shows all the rows which has the "Integrity_check_DBCC" value but I only want the ones with LastRunStatus equals to "Failed" not all possible status
SELECT
JOBSINFO.query('/Jobs/Job[contains(@JobName,"Integrity_check_DBCC")]')
FROM DBO.SQL_consolidated WHERE
(jobsinfo.exist('/Jobs/Job[contains(@JobName,"Integrity_check_DBCC")]') = 1);
Something like that but it does not work:
(jobsinfo.exist('/Jobs/Job[contains(@JobName,"Integrity_check_DBCC"')
AND (jobsinfo.exist('/Jobs/Job[contains(@LastRunStatus,"Failed")]') = 1)
(jobsinfo.exist('/Jobs/Job[contains(@JobName,"Integrity_check_DBCC"] AND [@LastRunStatus="Failed")]')= 1)
Thanks for your help,
[/INST]You were close, but the full condition should be in a single pair of square brackets.
sql
DECLARE @tbl TABLE(id int NOT NULL PRIMARY KEY,
xml xml)
INSERT @tbl(id, xml)
VALUES(1, '<Jobs>
<Job JobName="Formulatrix Database Index Rebuilding.Subplan_1" JobEnabled="true" ScheduleName="Formulatrix Database Index Rebuilding.Subplan_1" ScheduleFrequency="Weekly" ScheduleInterval="Sat " ScheduleTime="01:00:00" ScheduleTimeDescription="Starting at 01:00:00" NextRunTime="2023-05-13 01:00:00" LastRunStatus="Successful" />
<Job JobName="Integrity_check_DBCC" JobEnabled="true" ScheduleName="monthly_integrity_check_schedule_wave2" ScheduleFrequency="Every 1 Months" ScheduleInterval="First Sat" ScheduleTime="20:00:00" ScheduleTimeDescription="Starting at 20:00:00" NextRunTime="2023-06-03 20:00:00" LastRunStatus="Successful" />
<Job JobName="syspolicy_purge_history" JobEnabled="true" ScheduleName="syspolicy_purge_history_schedule" ScheduleFrequency="Daily" ScheduleInterval="Every Day" ScheduleTime="02:00:00" ScheduleTimeDescription="Starting at 02:00:00" NextRunTime="2023-05-09 02:00:00" LastRunStatus="Successful" />
</Jobs>')
SELECT * FROM @tbl
SELECT xml.query('/Jobs/Job[contains(@JobName,"Integrity_check_DBCC")]')
FROM @tbl
WHERE (xml.exist('/Jobs/Job[contains(@JobName,"Integrity_check_DBCC") and @LastRunStatus="Failed"]') = 1);</s>
|
<s>[INST]Hi Team,
We are in the process of troubleshooting T-SQL performance. We plan to check what was changed from the last execution.
As part of that, we are planning to compare the current and previous plan cache.
Please help us, how to get all the previous plan cache.
[/INST]](/users/na/?userid=a054b630-7ffe-0006-0000-000000000000) ,
SQL Server provides the following dynamic management views and functions that can be used to find out what is in the plan cache at any given time.
1. sys.dm_exec_cached_plans
2. sys.dm_exec_sql_text
3. sys.dm_exec_query_plan
The first dm_exec_cached_plans is a dynamic management view while the remaining two are dynamic management functions.
Let us use these functions and views to see what is in the SQL Server cached query plan. Execute the following query on your SSMS (SQL Server Management Studio):
SELECT cplan.usecounts, cplan.objtype, qtext.text, qplan.query_plan
FROM sys.dm_exec_cached_plans AS cplan
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS qtext
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qplan
ORDER BY cplan.usecounts DESC
A SELECT statement is used to select usecounts, object type, query text and an XML representation of the query plan of all the queries that currently reside in the query plan cache. Notice that the CROSS APPLY operator has been used to join the output from dynamic management views and functions. Finally, the result set is sorted in the descending order of the use counts.</s>
|
<s>[INST]Hello,
I installed sql 2016 Evaluation on a PC.
Now I have a sql 2019 license and I need to upgrade this sql to 2016 standard.
May I know any solution to complete this task?
Thanks.
[/INST]Now I have a sql **2019** license and I need to upgrade this sql to **2016** standard.
That's not possible, a license key is bound to the product version, you can not activate a SQL Server 2016 Eval with a 2019 product key. And a in-place version upgrade 2016=>2019 of an Evaluation Edition is not supported.
Uninstall 2016 and install 2019 with your product key.</s>
|
<s>[INST]Hi, I want to search CityCode
and want to see all Citycode and mapped related CityCodemapped data of Destination-CRT.
Example/Data and expected result. Criteria- IF search of Citycode is 'AAAA' in Select statement then expecting the following result which is in the table. Basically want to see all mapped related data of Citycode-AAAA with where clause-Destination=CRT. Table name is Mapresult.
Destination Date Citycode CityCodeMapped
CRT 1-1-2021 AAAA DUUU
CRT 1-1-2021 DUUU DUBB
CRT 1-1-2021 DBBB DUMM
CRT 1-1-2021 DUMM NULL
[/INST]](/users/na/?userid=d1f1d8c9-54cf-46d9-8589-f92ad4176860)
I modified the query according to your new requirements, you can give it a try.
```sql
;with T1 as(
select * from Mapresult where Citycode = 'AAAA' and Destination = 'CRT'
union all
select B.* from T1 as A inner join Mapresult as B
on B.Citycode = A.CityCodeMapped and B.Destination = A.Destination
),T2 as(
select C.* from Mapresult as C inner join T1 as D on C.CityCodeMapped = D.CityCodeMapped)
select * from T1
union
select * from T2;
```</s>
|
<s>[INST]Hi all,
If an automatic failover occur on an AG, will the connections of the applications be disconnected from the cluster or will this failover be totally transparent to the applications using it?
Best regards.
Carl [/INST]The applications will typically experience an error. A running query will fail, and if the application tries to reuse a connection from the connection pool that will also fail in many cases. But applications can be written to be resilient to such things. That is, they can capture such errors and retry.</s>
|
<s>[INST]Hi all,
I am trying to create a primary key dynamically on the target table.
I am trying to write a code to do this. However I am getting an error message when I try to run this code. How do I specify the variable next to add constraint. How do I declare a variable inside a dynamic slq code?
```
declare @sourcetablename nvarchar(max) = N'[dbo].[AAG00200]'
declare @targettablename nvarchar(max) = N'[dbo].[AAG00200_Test]'
declare @sql nvarchar(max)
set @sql = N'
IF OBJECT_ID(''tempdb.dbo.#TempTable'', ''U'') IS NOT NULL
DROP TABLE #TempTableName
select * into #TempTable from '+@sourcetablename+'
select * from #TempTable
declare @PKname nvarchar(max) = select Index_name from #TempTable where is_primary_key = 1
ALTER TABLE '+@targettablename+'
ADD CONSTRAINT ' +@PKname + ' PRIMARY KEY (ACTINDX)
drop table #TempTable'
EXEC sp_executesql @sql
```
Thanks
Nish[/INST]](/users/na/?userid=69b8b2fb-17ed-4da5-97a0-2053be6e71c2)
Try this query:
```sql
declare @sourcetablename nvarchar(max) = N'[dbo].[AAG00200]'
declare @targettablename nvarchar(max) = N'[dbo].[AAG00200_Test]'
declare @PKname nvarchar(max)
declare @sql nvarchar(max)
set @sql = N'
IF OBJECT_ID(''tempdb.dbo.#TempTable'', ''U'') IS NOT NULL
DROP TABLE #TempTableName
select * into #TempTable from '+@sourcetablename+'
SELECT @PKname = Index_name FROM #TempTable where is_primary_key = 1'
EXEC sp_executesql @sql,N'@PKname nvarchar(max) OUTPUT',@PKname = @PKname OUTPUT
SET @sql=N'ALTER TABLE '+@targettablename+' ADD CONSTRAINT '+@PKname+' PRIMARY KEY (ACTINDX)'
EXEC sp_executesql @sql
```</s>
|
<s>[INST]hi , can replication be limited to just some tables on the db or must it be on the entire source db? and if the source has timestamps, will there be any problem for sql to keep them as is on the target/replicated db?
[/INST]and if the source has timestamps, will there be any problem for sql to keep them as is on the target/replicated db?
I don't know this on the top of my head, and I would have to set up a test to find out. But setting replication for a quick test is a little messy, and some litter remain. So I have a different idea: **You** set up a test.
It's actually quite simple. If the original columns has the timestamp/rowversion data type, the columns in the replicated database must be binary(8). If the column in the subscriber is also timestamp/rowversion, the subscriber will have new values.</s>
|
<s>[INST]Hi everybody,
I need to arrange permissions for stored procedures in my databases in a way that people can execute a stored procedure if and only if they can execute the body of those stored procedures directly. For example, if people have select permissions and are denied the write permissions in a database, they could execute stored procedures that only have select statements and get permission denied on the stored procedures that manipulate data. I know that stored procedures are executed by default with the "WITH EXECUTE AS **CALLER**" clause. I tried OWNER and SELF keywords as well but they did not work.
I have the impression that this is not possible, but is there any way to do so? I appreciate your help a lot.
Regards
[/INST]this is possible Just make sure that the procedure has a different owner from all the tables and views being accessed by the procedure.
If a procedure access a table with the same owner as the procedure, SQL Server employs *ownership chaining* and does not perform any permission check. But if the owners of procedure and tables are different, there will be a permission check.</s>
|
<s>[INST]Hi,
I have a database with multiple user logins. Some of the data has been deleted by some user and I need to find out which user deleted the records.
What are the available options I have?
Thank you in advance.
Chamara[/INST]> What are the available options I have?
If you haven't implemented a logging, e.g. with DELETE trigger, then you have no options to get the informations afterwards; SQL Server don't log it on it's own.</s>
|
<s>[INST]I have SQL Server 2016, 2017 and 2019. Last February 14, two security updates have been released per version. You may refer to the KB list below. Upon running Windows Updates one security update for each SQL version has not been installed. Does it have something to do with the build number of the not installed KBs being lower than the installed ones?
**SQL 2016**
KB5021128
KB5021129 **X**
**SQL 2017**
KB5021126
KB5021127 **X**
**SQL 2019**
KB5023049
KB5021124
KB5021125 **X**
[/INST]It seems that one of set the patches for instances with Azure Connect Feature Pack, and one is for those without. The issues addressed appears to be the same.</s>
|
<s>[INST]I have a DB that I can access in MS SQL Server Management Studio and from an application that I used to create the DB using code first. I am trying to connect to that DB via a different app and my connection fails every time. In Visual Studio \> SQL Server Object Explorer it lists the SQL Server as "(localdb)\\MSSQLLocalDB". When I try to use a single "\\" in my connection string VS prompts me saying unrecognized escape sequence and won't build. When I use "\\" I can't connect. What am I missing?
string connStr = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=myDatabaseName;Integrated Security=True";
SqlConnection con = new SqlConnection(connStr);
try
{
con.Open();
MessageBox.Show("Connected");
}
catch
{
MessageBox.Show("Failed");
}
con.Close();
[/INST]I actually resolved this by using "Database=" instead of "Initial Catalog=". !</s>
|
<s>[INST]hi Folks,
One of our application developer wants to run queries against msdb and reportserver database using linked server. is it advisable to run query against msdb and reportserver databases using linked server? can someone give me cons of doing this?
[/INST]I can't really see any issues if you set up the linked server with self-mapping. That is, to be able run these queries, he needs to have permissions in msdb and the ReportServer database when he logs in directly. Using a linked server with self-mapping.
If the developer does not have permission and hope that you will set up a linked server with login-mapping - just say no.</s>
|
<s>[INST]We have a SQL Server 2017 Enterprise Core edition with no SA in virtualized environment. This VM has been assigned 8 vCPU. This VM is hosted on three physical servers in failover cluster. I would like to know from licensing expert if we are covered with license in our setup in case ofVM failover to another physical server in the same cluster.
[/INST]I contacted Microsoft VLSC support and he advised me to contact reseller. They can only read the licensing document which only mentioned about SQL fail-over cluster scenario. There is no example of using SQL server on VM in fail-over cluster environment the licensing documents.</s>
|
<s>[INST]Hi Team - I am trying to create to create blank column while writing a SELECT like below.
Could you help resolve the issue below ?
```
SELECT
*
, '' AS PROCESSING_FLAG
INTO #CA_CONTRACTLINES_FLAGPROCESSING_STG
FROM #CA_CONTRACTLINES
#CA_CONTRACTLINES_FLAGPROCESSING_STG),its giving me the below error.
UPDATE #CA_CONTRACTLINES_FLAGPROCESSING_STG
SET PROCESSING_FLAG = 'C!'
String or binary data would be truncated.
SELECT
*
, NULL AS PROCESSING_FLAG
INTO #CA_CONTRACTLINES_FLAGPROCESSING_STG
FROM #CA_CONTRACTLINES
UPDATE #CA_CONTRACTLINES_FLAGPROCESSING_STG
SET PROCESSING_FLAG = 'C!'
Conversion failed when converting the varchar value 'C!' to data type int.
AS PROCESSING_FLAG
```
[/INST]Try
sql
SELECT
*
, cast(NULL as varchar(10)) AS PROCESSING_FLAG -- specify desired column's type
INTO #CA_CONTRACTLINES_FLAGPROCESSING_STG
FROM #CA_CONTRACTLINES</s>
|
<s>[INST]Hi All,
Is specifying locking hints and set lock_timeout is a good thing or bad thing? I see a lot of this kind, in the app code?
Please share your thoughts and view points.
We are using SQL 2017 EE.
SET LOCK_TIMEOUT ? UPDATE TNAME WITH (ROWLOCK) SET CREATE_DATE = CREATE_DATE WHERE ROWID_OBJECT = ?
Thanks,
Sam
[/INST]Lock hints like ROWLOCK can be needed at times, but they should be used sparingly, not as a matter of routine. The ROWLOCK hint, specifically is a little dangerous. It forces row locks to be taken, and it may seem like an appealing easy way out if you have problems with SQL Server taking page or table locks causing blocking issues. However, there is a reason why SQL Server takes locks on a higher level: to preserve memory. So if you are forcing row locks and it is a popular query that is executed by many users concurrently and it accesses many rows, SQL Server could run out of memory.
A better approach if you have these sort of problems is to tune the query or add indexes that support the query.
There are still some scenarios where ROWLOCK makes perfect sense, but they will have to count as advanced. And as with all advanced feature, you need to know what you are doing.
When it comes to SET LOCK_TIMEOUT, I'm a little puzzled by the question mark, because SET LOCK_TIMEOUT does not seem to accept a variable as argument. In any case, there are certainly situations where lock timeouts can come in handy. Say that you want to run an operation that needs a table lock (because you will update the entire table). Say that you submit this statement, but it is blocked by a long-running SELECT. Because your query is first in the queue, it will block other SELECT queries that come in later, of which many or all would be short-running, if they only got the chance. You can prevent this situation by saying SET LOCK_TIMEOUT 1000 to wait for a second and give up, wait a while to retry later.
As you may understand, this is a quite specialised scenario, and it is a not a very widely used feature. Generally, I would say that you would only use lock timeouts if you have a reason for it. It is nothing you do on a whim.</s>
|
<s>[INST]Hi,
I'm upgrading our SQL Server and Windows Server to 2019, and wondering if I need to purchase more than one SQL User Cal with my scenario.
We have an Application that uses RDP to connect each physical workstation to a single Application Server and an SQL Server.
We use the same Domain user profile simultaneously at 20 workstations that accesses the Application & SQL Servers, each workstation is configured within the application to connect to the SQL Server database using the same username & password.
Do I need to purchase 20 SQL User Cals (1 for each workstation), or can I just purchase 1 User Cal for the Domain user profile being used?
Thank you![/INST]I contacted MS, their response was that I would need to purchase a device Cal for each workstation, and that we wouldn't be in compliance if we only used a single User Cal even if it was the only User Domain account used.</s>
|
<s>[INST]Hello.
I have the following table. Now I need to query out the records in each group where value1 and value2 have the same value sorted from smallest to largest.
For example, according to the table below, I can get (1, 12, 20).
create table sourcetable(groupid int,value1 int,value2 int)
insert into sourcetable values(1,10,25),(1,50,15),(1,12,20),(1,15,30)
Thanks.[/INST]microsoft.com/en-us/users/na/?userid=b49a71b0-0b45-41bd-a6bf-4a12570846f6)
If I understand correctly, you can try this query.
```sql
;with CTE as(
select *,row_number()over(partition by groupid order by value1) as num1,
row_number()over(partition by groupid order by value2) as num2 from sourcetable)
select groupid,value1,value2 from CTE where num1 = num2;
```</s>
|
<s>[INST]Good day,
I am trying to understand how I can catch blocked_process_report_filtered. I did test with blocked_process_report (without filtered) and it works as planned but at the same time no blocked_process_report_filtered events were caught.
Does somebody know how to catch this specific blocked_process_report_filtered event?
I use standalone instance of Enterprise Editition of SQL Server 2019.
[/INST]I tested this now on SQL 2019 as well. And indeed, on SQL 2019, this event does not fire. But as I said, it fired on SQL 2022 when I tested.
I guess then that this is a new event, introduced in SQL 2022. Somehow the metadata about the event has leaked into SQL 2019, but the event itself has not been backported.</s>
|
<s>[INST]Please see attached. The network share is inaccessible, and I have zero clue what the problem is since it is otherwise accessible by all means from all servers. Why does SQL Server even need access to this share? I gave it permissions (NT SERVICE\MSSQL$CHISQLJAY1 - the account for my instance), but the failure is still evident.
Why do I even need this stupid backup directory? I don't want a backup. I don't need it. I just want to migrate my data to a new SQL Server instance. If the transfer fails, who cares?
I'm spending 99% of my time on a problem that has less than 1% relevance to what I want to do.
[/INST]microsoft.com/en-us/users/na/?userid=828d87c2-c57c-4e21-9d4f-11d46af1270e)
I don't see your attachment, maybe it's missing, please upload it again. As Olaf said, we need more information to help you solve the problem.</s>
|
<s>[INST]Hello All,
I noticed few differences in data files sizes for normal database and Always ON configured database.
When I add the database to Always ON, I noticed like the free space is quite less but at the same time when I restored the same database to standalone sql server I observed like free space on the data files is more.
Can anyone explain me about this?[/INST]](/users/na/?userid=a0d01cd2-4a3c-428d-be87-4243edd38ddb),
The difference in free space between an on-premises SQL Server database and an Always On configured database in SQL Server 2019 can be attributed to how SQL Server handles free space in different scenarios.
In an on-premises SQL Server database, free space within data files is managed by the SQL Server storage engine. When data is deleted or truncated, the space is marked as free within the data file, but it is not immediately released back to the operating system. Instead, the space is kept within the data file as free space, which can be reused for new data in the future. This is known as "free space reclamation" and is a standard behavior in SQL Server.
On the other hand, in an Always On configured database, which is part of a SQL Server Availability Group (AG), free space is managed differently. In an AG, multiple SQL Server instances work together to provide high availability and fault tolerance. Data changes made on the primary replica are synchronized to one or more secondary replicas. The secondary replicas apply these changes to their own copies of the database. However, the secondary replicas do not perform free space reclamation. Instead, the free space is preserved in the data files to ensure consistency with the primary replica.
As a result, when you compare the free space in data files between an on-premises SQL Server database and an Always On configured database, you may see that the on-premises database has more free space, while the Always On configured database has less free space. This is because the free space in the Always On configured database is being preserved to maintain consistency among the replicas in the Availability Group.
It's important to note that this behavior can be different when you restore an Always On configured database to a standalone SQL Server instance, as the free space is reclaimed by the storage engine in the standalone instance, leading to potentially more free space in the data files. However, in the context of an Always On Availability Group, the behavior is as described above to ensure data consistency among the replicas.</s>
|
<s>[INST]We have a dev that used to use SSMS in order to debug code that was related to SQL. I guess MS has taken that piece out of SSMS and now they are supposed to do this with Visual Studio. Problem is, now we can't seem to get that to work right.
Each time they try with VS19 to a SQL 2019, the following error comes up:
*"Unable to start the Transact-SQL debugger, could not connect to the Database Engine instance '<instance name>'. Make sure you have enabled the debugging firewall exceptions and are using a login that is a member of the sysadmin fixed server role. The RPC server is unavailable."*
The firewall is disabled and according to what I have read, the debugging person's account needs to be in the SQL Server's "sysadmin" role. Done that and also made that user the db owner for good measure. FYI, I've tried using domain group and adding them to the group and also just using their individual domain accounts.
Everything I try reaps the same error message.
Please advise.
[/INST]So I don't know the details what the programmers are doing but when I suggested the Print and Select option, they are aware of that but said that that is too simplistic for what they are doing.
For what ever reason, I had them try again and today it worked! I didn't make any additional changes. So the only thing that comes to mind was that maybe some log out and log in process needed to occur after the permissions were set?
Thanks for the feedback</s>
|
<s>[INST]I am giving my table Structure below
**tblOrganization**
OrganizationId
OrganizationName
OrganizatioEmail
**tblLocation**
LocationId
OrganizationId Here may contain multiple location aginist one Organization
LocationName
**tblContact**
ContactId
OrganizationId Here may contain multiple contact aginist one Organization
ContactName
**tblSpecialities**
SpecialityId
SpecialityName
**tblOrganizationSpecialities**
SpecialityId Mapping table Organization and Specialities. Here may contain multiple Specialities aginist one Organization
OrganizationId
Please help me write sql query to get below output
Expected Result
```json
{
"Data": [{
"organizationId": 333,
"organizationName": "Org3",
"OrganizatioEmail": "[email protected]",
"location": [
{"LocationName": "Location1"},
{"LocationName": "Location2"},
{"LocationName": "Location3"}
],
"contact": [
{"ContactName": "ContactName1"},
{"ContactName": "ContactName2"},
{"ContactName": "ContactName3"}
],
"specialities": [
{"specialityName": "Speciality1"},
{"specialityName": "Speciality2"},
{"specialityName": "Speciality3"}
]
}]
}
```
[/INST]Try the following code:
SELECT
OrganizationId,
OrganizationName,
OrganizatioEmail,
(
SELECT LocationName
FROM tblLocation
WHERE OrganizationId = O.OrganizationId
FOR JSON PATH
) AS Location,
(
SELECT ContactName
FROM tblContact
WHERE OrganizationId = O.OrganizationId
FOR JSON PATH
) AS Contact,
(
SELECT S.SpecialityName
FROM tblOrganizationSpecialities AS OS
INNER JOIN tblSpecialities AS S ON OS.SpecialityId = S.SpecialityId
WHERE OS.OrganizationId = O.OrganizationId
FOR JSON PATH
) AS Specialities
FROM tblOrganization AS O
FOR JSON PATH;</s>
|
<s>[INST]Dear All,
We were trying to create Database Master key for one of the User database, but its getting failed with below error.
"An Error occured During Master key Decryption"
We are not sure above Server Master Key Password also. Any help would be appreciated.
[/INST]Try too Regenerate the service master key by using the Transact-SQL statement
ALTER SERVICE MASTER KEY FORCE REGENERATE</s>
|
<s>[INST]Hi:
We have some old stored procedures and we noticed that whoever wrote this had limited knowledge of database. They are dropping and recreating physical tables (TMP_...) within stored procedures instead of using temp tables (#) or table variables. Is there any advantage of using physical table vs temp or variable tables?
Is there any security risk and Performance issue?
Before we give any recommendation for making changes to those stored procedures I wanted to know from experts here what we are going to propose is right solution and why recreating physical table for temporary storage is bad idea.
Thanks!
[/INST]microsoft.com/en-us/users/na/?userid=5c4f6c77-bf73-4f8c-9e34-0b798f0d1e1e)
Physical tables are typically created to store application data. They store all the persistent data that the application needs.
Temporary tables are used to store temporary information. Most of the time, you don't need to keep your data after you've processed it. For example, a stored procedure might store intermediate results in a temporary table and process them for better performance.
In your case, you need to drop and rebuild the table. So using physical tables is not appropriate.</s>
|
<s>[INST]Dear Folks,
is it possible to create database snapshot on secondary read replica in AG with resource governor limiting queries from application.?[/INST]I created the database snapshots for one of our database which is of almost 4.0 TB, I observed when the third party tool BryteFlow get connected and started fetching queries latency on secondary replica slowly increased by approx. 7000 seconds and after that database snapshot went into suspect mode.
When I tried to search logs I found the error **< Z:\Snapshots\dbname_ss.ss: Operating system error 665(The requested operation could not be completed due to a file system limitation) encountered. Error: 17053, Severity: 16, State: 1.>**
I also created resource governor for that tool not to take more than 15% CPU and 25% memory and DOP =2
is there any way I can meet this requirement ?</s>
|
<s>[INST]when run sql statement below it give me error
```
SELECT
p.ApplicationId,
ServerName = STUFF((
SELECT distinct ',' + pt.Server_Name
FROM [dbo].[ServerNames] pt
INNER JOIN #t1 t
ON pt.ServerID = t.ServerID
-- WHERE pt.Prod_IDM = p.Prod_ID
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, ''),
[DataBase]= STUFF((
SELECT distinct ',' + pt.[DB_Name]
FROM dbo.[DataBase] pt
INNER JOIN [dbo].[ServerNames] t
ON pt.ServerID = t.ServerID
WHERE p.ServerID = t.ServerID
group by p.ServerID
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM #t1 p
group by p.ApplicationId
ORDER BY p.ApplicationId;
```
Msg 8120, Level 16, State 1, Line 24
Column '#t1.ServerID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
so How to solve this issue
also another issue i need to solve
i need to display comma separated after first item because on statement above it display before first item[/INST]](/users/na/?userid=c5d17fe4-34a1-454e-bbe2-5d2ea27b1d8c)
If you are able to use STRING_AGG, then check this query:
```sql
;WITH CTE1 AS
(
SELECT ApplicationId,STRING_AGG(Server_Name,',') AS Server_Name
FROM #t1 t INNER JOIN [dbo].[ServerNames] s ON s.ServerID = t.ServerID
GROUP BY ApplicationId
),CTE2 AS
(
SELECT ApplicationId,STRING_AGG([DB_Name],',') AS [DB_Name]
FROM #t1 t INNER JOIN [dbo].[DataBase] db ON db.ServerID = t.ServerID
GROUP BY ApplicationId
)
SELECT C1.ApplicationId,C1.Server_Name,C2.DB_Name
FROM CTE1 C1 JOIN CTE2 C2 ON C1.ApplicationId=C2.ApplicationId
```</s>
|
<s>[INST]Hi, How I can get the following desired result without mentioning column's name in the query.
Select * from country
CCode CName CPost CDest CSET CPOS CJOH
001 AU L1 RE 1 2 CEN
Desired Result:
('001','AU','L1','RE','1','2','CEN')
[/INST]This can be done through SSIS (Import/Export Wizard from SSMS).
Export table data from your database to a text file you defined.
Choose no header row for the text file (uncheck the box: Column names in the first row) and with text qualifier you choose (single quote).
You can run the package immediately or save it for later run.</s>
|
<s>[INST]Hello everyone,
I was trying to create a auto restore database script. to restore the database from one database to another database. i created the script and job which is working fine to restore the database which is
use master
RESTORE DATABASE [databse name]
**FROM DISK = N'file path\backup database_name.bak'**
WITH MOVE N'logical__name' TO N'file path\backup database_name.mdf',
MOVE N'logical_name' TO N'file path\backup database_name.ldf',
REPLACE;
go
this query is running fine and restoring the database but i need to do this manually, means i need to give the file name to choose latest .bak file but when i will set it for auto restore file name will be different and job will not find it and there will be plenty of .bak because backup will be going on everyday, so i want to write the query which helps me to select latest .bak file automatically so when the jobs will run it will pick the latest file and restore that to the database.
Can anyone help me to modify this query.
[/INST]You can use the system tables backupmediafamily and backupset in msdb to find out the latest backup file:
sql
DECLARE @backup_filename nvarchar(128);
DECLARE @physical_device_name nvarchar(260);
SELECT TOP 1
@backup_filename = bs.[name],
@physical_device_name = bf.[physical_device_name]
FROM [msdb].[dbo].[backupmediafamily] AS bf
INNER JOIN [msdb].[dbo].[backupset] AS bs ON bs.[media_set_id] = bf.[media_set_id]
WHERE bs.[type] = 'D' AND bs.[database_name] = 'YOUR_DATABASE_NAME'
ORDER BY bs.[backup_finish_date] DESC;
SELECT @backup_filename, @physical_device_name;</s>
|
<s>[INST]Were having a few issues with SQL Server on our implementation of Oracle Primavera.
Sql server database is using a self signed cert and Force Encryption is Yes.
(Weblogi / oracle bit...) When running startWeblogic.cmd i get error: "The SQL Server login requires an SSL connection". When force encryption is No then adminserver starts..
I have had many calls with Oracle Support but we cannot find a way around this. **One suggestion, and this is why I'm asking on this forum, is that there may be a SQL Server driver that we need to download to get this to work.**
Any suggestions appreciated, happy to field questions but am hoping this triggers something in one of you clever peeps!
[/INST]I think we've found a solution, all related to Oracle products.
For the sake of completion, i thought i'd add some more comments in case someone else goes looking.
We couldn't build a WebLogic domain with OHS/EM etc when force encrypt was Yes, but could build the EPPM domain.
OHS not utilised, so port numbers are required for the EPPM login
I realise that in a SQL Server group, that's not much use - but someone in our boat might stumble across the problem.
No API being used</s>
|
<s>[INST]I am attempting an In-Place upgrade from SQL Server 2016 (13.0.5201.2) to SQL Server 2019 RTM. I have uninstalled Microsoft SQL Server 2012 Native Client & Microsoft SQL Server 2014 Native Client. I also uninstalled SSMS 17.9 and no other SSMS is installed. I turned on the Windows Installer service, copied the SQL Server 2019 installation files to C root drive and restarted the server. When I run the installer the first error encountered is "Exception has been thrown by the target of an invocation.". If I click the OK button it resumes and encounters a 2nd error "The document specified by its root path '/Extension/Agent/AgentPreviousRegPath' does not exist in data store.". If I click OK button I encounter a 3rd error listed below.
Install_sql_engine_core_inst_Cpu64_Action : Sqlmsirc_NotifyFeatureStates_64
-------------------------------------------------------------------------------------------
There was an error attempting to remove the configuration of the product which prevents any other action from occuring. The current configuration of the product is being cancelled as a result.
Next the Complete with failures window is displayed (See Below).
Database Engine Services -- FAILED
SQL Browser -- Succeeded
SQL Writer -- Succeeded
Integration Services -- Succeeded
SQL Client Connectivity SDK -- Succeeded
SQL Client Connectivity -- Succeeded
Setup Support Files -- Succeeded
My summary file -- Exit code (Decimal): -2146232828
----------------------------------------------------------------------
Feature: Database Engine Services
Status: Failed
Component name: SQL Server Database Engine Services Instance Features
Component error code: 25012
Error description: There was an error attempting to remove the configuration of the product which prevents any other action
from occuring. The current configuration of the product is being cancelled as a result.
Component name: SQL Server Database Engine Services Instance Features
Component error code: 0x80131604
Error description: Exception has been thrown by the target of an invocation
Component name: SQL Server Database Engine Services Instance Features
Component error code: 0x84B20001
Error description: The document specified by its root path '/Extension/Agent/AgentPreviousRegPath' does not exist in data
store.
[/INST]I found the issue. I am currently performing the in-place upgrade on a cloned VM but it's not attached to our domain. I had to change the SQL Server service account since we use a domain account to use a local service account. I had stopped the SQL Agent service and pretty much forgot about it. However, it to used a domain account and I had to change it also to use a local service account and also started the SQL Agent service and this resolved the issues. !</s>
|
<s>[INST]I am seeing a lot of page splits happening on this table.
A lots INSERTS and DELETES happens on this table. Its a very high transactional table. A lot of concurrent operations happens on this table. Is there anything can be done to fix at table level to avoid page splits?
CREATE TABLE [dbo].[Repository_locking_table](
[ROWID_LOCK] [nchar] NOT NULL,
[CREATE_DATE] [datetime2] NOT NULL,
[CREATOR] [nvarchar] NOT NULL,
[LAST_UPDATE_DATE] [datetime2] NULL,
[UPDATED_BY] [nvarchar] NULL,
[ROWID_TABLE] [nchar] NOT NULL,
[LOCK_GROUP_STR] [nvarchar] NOT NULL,
[LOCK_EXCLUSIVE_IND] [bigint] NOT NULL,
[JOB_TYPE_STR] [nchar] NOT NULL,
[LOCK_QUERY_SQL] [nvarchar] NULL,
[MODULE_NAME] [nvarchar] NULL,
[INTERACTION_ID] [nvarchar] NULL,
CONSTRAINT [PK_Repository_locking_table] PRIMARY KEY NONCLUSTERED
(
[ROWID_LOCK] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)
GO
Thanks,
Sam
[/INST]This is a small table. There are only two rows in the table. Interesting enough, a SELECT * on the table results in 285 logical reads. This suggests that there is a whole lot of empty space in the table.
Judging from the name, the purpose of the table is to lock things in some roll-your-own locking scheme. I would guess that rows are deleted and inserted quite regularly.
There was a suggestion to play with the fill factor, and indeed if you have a table where rows are inserted both here and there, setting a fill factor of 80-90 when you rebuild the index can be a good idea. However, this applies to a table where most of the rows stay around, which does not seem to be the case here. And the actual fill factor in this case is very low, below 1.
Given that this is a vendor database, I don't think you can do much with this table. Overall, if you have performance issues with a vendor application, there is all reason to involve the vendor. If there are performance issues with this table C_REPOS_APPLIED_LOCK, this probably requires a new way of thinking in the application.</s>
|
<s>[INST]Hi:
Need help with getting max date of previous month. I think below SQL, I want the output to be 02/27/2023. If I use the EOMMONTH then it gives me the last day of previous month end.
```
DECLARE @tblData TABLE
(LNID INT,
AC_CD VARCHAR(100),
AC_DT DATETIME)
INSERT INTO @tblData VALUES (101,'CPRCLOSE','01/31/2023')
INSERT INTO @tblData VALUES (100,'CPRCLOSE','02/27/2023')
INSERT INTO @tblData VALUES (120,'CPRCLOSE2021','02/26/2023')
INSERT INTO @tblData VALUES (121,'CPRCLOSE2022','03/01/2023')
INSERT INTO @tblData VALUES (200,'CPRCLOSE','03/02/2023')
SELECT MAX(AC_DT)
FROM @tblData
WHERE AC_CD LIKE 'CPRCLOSE%'
AND AC_DT = EOMONTH(DATEADD(month, -1, GETDATE()))
```
[/INST]SELECT MAX(AC_DT)
FROM @tblData
WHERE AC_CD LIKE 'CPRCLOSE%'
AND AC_DT > EOMONTH(DATEADD(month, -2, GETDATE()))
and AC_DT <= EOMONTH(DATEADD(month, -1, GETDATE()))</s>
|
<s>[INST]Hi All,
When today I was installed Sql Server Management Studio latest version (18.8) in my PC, I found that it won't showing SSMS IDE instead I am only getting option to connect the DB using Azure Data Studio.
Also when I search in C drive Program folder for ssms.exe I did not found anything.
So I want to know Is SSMS IDE was retired or any issue with that setup ?
Thanks,
Sk.[/INST]I have did so many thing but I could not see that file it's seems like some thing broken.
I have verified above path but I was not able to see the SSMS.exe file.
So I have restarted my machine and still also I am not able to see that file.
Then I have deleted registry key for ssms and cleared the temp file and re-install it again and then it's worked for me.</s>
|
<s>[INST]Hi guys,
I would like to know how to get the version information of SSMS?
kind regards
Marco[/INST]I just want to know the version info which is installed.
I found this
get-childitem <path where ssms.ex is located>\ssms.exe | Format-List VersionInfo</s>
|
<s>[INST]Here is what I am concerned:
If I have a transaction inserts 1 million records using the getdate() function, will there be different timestamp, or will the inserted create_time always be the same?
```
insert into table1(id,create_time) select id,getdate() from table2
```
Thanks in advance!
[/INST]microsoft.com/en-us/users/na/?userid=772119a2-1f56-46b7-abb1-4ad3b69358cc)
As far as I know, `Getdate()` returns the same value in one single statement.
If you want to ensure the same inserted create_time, it is recommended to assign getdate to a parameter and then use this parameter in the insert statement.</s>
|
<s>[INST]I'm trying to retrieve values from fields using the like statement. But I understand it's not possible to use multiple like statements in an AND statement
For example I would like to return output from the following table where values in the field job_title contain values such as "Trading", "Group"
```
SELECT
*
FROM dbo.investmgmt
WHERE investmgmt.job_title LIKE '%Trading%'
AND investmgmt.job_title LIKE '%Group%'
```
But I'm not getting any output.
Can someone shed some light on the situation
Below is some sample data
```
CREATE TABLE #tmpTable (
job_title varchar(250))
INSERT #tmpTable VALUES
('Managing Director at Pacific energy and investment limited'),
('Data Management Analyst at Kuwait Investment Office'),
('Platform Service Manager at Seven Investment Management LLP (7IM)'),
('Analyst at Cheyne Capital'),
('Investment Banking Analyst at BMO Capital Markets'),
('Headhunter - Investment Banking Change Management'),
('Managing Director'),
('Investment Analyst at Pluto Digital'),
('Quantitative Strategy & Trading | Multi-Strat Hedge Fund | Macro Economics | Machine Learning | Derivatives | Digital Assets'),
('Senior Advisor at Generation Investment Management'),
('Investment Director at Hampton Group')
SELECT * FROM #tmpTable
```
[/INST]Use OR instead of AND to get the values you want.</s>
|
<s>[INST]hi Folks,
I have a weird requirement. Is it possible to create a custom role that has all the permissions like sysadmin ? Basically i want to create a custom role like sysadmin but by excluding certain permissions like "alter database" "control" permission etc.
Thank you
[/INST]it is not possible. Santhi's example above have several errors. One is that the role is added to sysadmin. Once you are in sysadmin, all performance checks are voided. So you cannot revoke or deny anything from sysadmin.
There is also the permission CONTROL SERVER, which gives you all permissions on the box, and in this case you can do:
```
USE master
go
CREATE LOGIN TestAdmin WITH PASSWORD = '==)Y/BNBÖ*ÄSADEääsdb'
GRANT CONTROL SERVER TO TestAdmin
DENY ALTER ANY DATABASE TO TestAdmin
go
EXECUTE AS LOGIN = 'TestAdmin'
go
ALTER DATABASE model SET RECOVERY FULL -- Results in permission error.
go
REVERT
```
However, there are two problems:
1. While CONTROL SERVER gives you all permissions, there are still only actions that can be performed by a member of the sysadmin role.
1. It is very easy for TestAdmin to circumvent the DENY
```sql
EXECUTE AS LOGIN = 'TestAdmin'
go
REVOKE ALTER ANY DATABASE TO TestAdmin
go
CREATE LOGIN ExtraUser WITH PASSWORD = 'HahaSaidTheClown'
GRANT CONTROL SERVER TO ExtraUser
go
EXECUTE AS LOGIN = 'ExtraUser'
go
ALTER DATABASE model SET RECOVERY FULL
go
REVERT
go
REVERT
DROP LOGIN TestAdmin
DROP LOGIN ExtraUser
```
That is, TestAdmin can create a new login, grant that login CONTROL SERVER, impersonate that login and then perform the forbidden action.</s>
|
<s>[INST]I have a table with a xml column.
I need to add a new node to the xml but it needs to go into a specific location.
Here is an example. Not our actual data but the structure is similar.
I want to add the following between Milk and Lettuce.
<Product>
<Category>Vegetable</Category>
<Name>Carrots</Name>
</Product>
Using SQL, how would I insert this. I've tried using the .modify method but can't get the syntax correct.
```
<Table>
<Product>
<Category>Dairy</Category>
<Name>Milk</Name>
</Product>
<Product>
<Category>Vegetable</Category>
<Name>Lettuce</Name>
</Product>
</Table>
```
[/INST]sql
DECLARE @x xml = '<Table>
<Product>
<Category>Dairy</Category>
<Name>Milk</Name>
</Product>
<Product>
<Category>Vegetable</Category>
<Name>Lettuce</Name>
</Product>
</Table>'
SET @x.modify('insert <Product><Category>Vegetable</Category><Name>Carrots</Name></Product> after (/Table/Product[Name="Milk"])[1]')
SELECT @x</s>
|
<s>[INST]This is a newly install SQL engine with SSMS 18.8.
# When I try to run any of the Standard reports like Disk Usage and same thing when running the integration standard report I get the following error....
TITLE: Microsoft SQL Server Management Studio
------------------------------------------------------------------------
An error occurred during local report processing. (Microsoft.ReportViewer.WinForms)
------------------------------------------------------------------------
ADDITIONAL INFORMATION:
The definition of the report '' is invalid. (Microsoft.ReportViewer.Common)
------------------------------------------------------------------------
An unexpected error occurred in Report Processing. (Microsoft.ReportViewer.Common)
------------------------------------------------------------------------
# The process cannot access the file 'C:\\Users\*\*\*\*\*\*\*\\AppData\\Local\\Temp\\expression_host_6ae6778716daa4c0abe594cb552c80899.dll' because it is being used by another process. (mscorlib)
The DB engine is up to date
SSMS is up to date
Server was rebooted
That temp file is not used by anything else even if that message says so, I have check with ProcessExplorer
What am I missing???
[/INST]Found the issue.
SQL Server created the temp file in local "C:\Users***\AppData\Local\Temp\..."
In a split second the antivirus software took a lock on to scan it at the same time SQL Server was about to read it or execute.
The antivirus software did not find any issues with it but by the time it release it it was too late.
Resolution: tune antivirus software.</s>
|
<s>[INST]I have a table that I need to *append* a column to. The data for the column will come from a new table that is related by the customer number. So I'll create col B in the existing table. I want to populate it with the related data from col C of another table. What is the best way to accomplish this?
[/INST]Try something like this:
```SQL
alter table Table1 add B int null
update t1
set B = t2.C
from Table1 t1 inner join Table2 t2 on t2.customer_number = t1.customer_number
```
In this example, the columns *B* and *C* are integer numbers.</s>
|
<s>[INST]I will often be working with queries with multiple servers and databases open in SSMS at the same time. When I run a query, I know I can use [DATABASE] to run in a specific, but SS seems to get confused about which SERVER I want to run on. I'm logged into several different servers in SSMS (all with different credentials). How can I FORCE my query to execute ON SERVER-A using DB-B?
[/INST]query windows are tied to server connection. you can change the database (use database) from the drop down. to change the connection, in the query window right click and pick:</s>
|
<s>[INST]Hello!
I need to count the quantity of each category within 7 days.
This is my table.
Create table worktable1(Group char(5),Category_ID varchar(max))
Insert into worktable1 values
('A','hjb,fch,khi,vgd,ubf,ksw'),
('B','vgd,ubf,ugv,loj,dgx,lqa,gcs'),
('C','ohd,phz,bdq,mfs,cih'),
('A','ksw,fch,zsd,kyf,vcn'),
('B','gcs,loj,ubf,dhc'),
('C','bdp,ihz,ohd,hfd'),
('A','vcn,ksw,zsd,fch,hib');
('A','hjb') are the groups I need to count, so the Category_ID column needs to be disassembled.
Could you show me how to count the number of ('A', 'hjb')?
Thanks!
[/INST]microsoft.com/en-us/users/na/?userid=5628d4c6-7d6d-4f1a-9646-c593af4070d2)
If I understand correctly, you can try this query.
```sql
;with CTE as(
select [Group],value from worktable1 cross apply STRING_SPLIT(Category_ID, ','))
select [Group],value,count(*) as nums from CTE group by [Group],value;
```</s>
|
<s>[INST]below is store procedure
USE [SilverRags]
GO
/****** Object: StoredProcedure [dbo].[SP_insert_Bale] Script Date: 12/31/2021 5:02:50 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Proc [dbo].[SP_insert_Bale_M]
@Bale_ID varchar(12)=null,
@item_code int=null,
@Bale_Weight decimal(10,2)=null,
@Bale_Qty int=null,
@Bale_Date date=null,
@Bale_Time time(7)=null,
@IPAddress varchar(50)=null,
@Bale_type int=null,
@Empid int=null,
@Machineno int=null
as begin
Insert into tbl_Bale_prd(bale_id,item_code,bale_weight,Bale_qty,Bale_Date,Bale_time,IpAddress,empid,Bale_Type,Machine_no) values
(@bale_id,@item_code,@bale_weight,@Bale_qty,@Bale_Date,@Bale_time,@IpAddress,@empid,@Bale_Type,@Machineno)
end
IF i mentioned Bale_qty 10 ,then 10 row insert into table.
[/INST]Hi,
About this sentence “IF i mentioned Bale_qty 10 ,then 10 row insert into table.”
Do you mean that when the _qty is 10, insert 10 rows of the same data, when the _qty is 5, insert 5 rows of the same data.
If so,please check this:
ALTER PROC dbo.SP_insert_Bale_M
AS
BEGIN
INSERT INTO #tbl_Bale_prd
SELECT TOP (@Bale_qty) @bale_id,@item_code,@bale_weight,@Bale_qty,@Bale_Date,@Bale_time,@IpAddress,@empid,@Bale_Type,@Machineno
FROM master.dbo.syscolumns
END
EXEC dbo.SP_insert_Bale_M @Bale_Qty =10
If not, please share us your detailed result.</s>
|
<s>[INST]Hi Team -
Truncate TABLE A
INSERT INTO TABLE A ( Column1, Column12,Column13,Column14,Column15,Column16,Column17,Column18)
Select Column1, Column12,Column13,Column14,Column15,Column16,Column17,Column18 FROM OPENQUERY(ORACLE,' SELECT Column1, Column12,Column13,Column14,Column15,Column16,Column17,Column18 FROM OracleTable')
This is my current query but i got a request not to truncate the table until i see a change, insert records, update etc..
So could you please help me how to write the MERGE script in this case ?
[/INST]](/users/na/?userid=89c36154-0579-49d8-b331-26cb6342b7b5)
Try this:
```sql
MERGE TableA AS tgt
USING (Select Column1, Column12,Column13,Column14,Column15,Column16,Column17,Column18
FROM OPENQUERY(ORACLE,' SELECT Column1, Column12,Column13,Column14,Column15,Column16,Column17,Column18 FROM OracleTable')) as src
ON (tgt.Column1 = src.Column1)
WHEN MATCHED
THEN UPDATE
SET Column12=src.Column12,
Column13=src.Column13,...
WHEN NOT MATCHED BY TARGET
THEN INSERT (Column1, Column12,Column13,Column14,Column15,Column16,Column17,Column18)
VALUES (src.Column1,src.Column12,src.Column13,src.Column14,src.Column15,src.Column16,src.Column17,src.Column18)
WHEN NOT MATCHED BY SOURCE
THEN DELETE
OUTPUT $action, Inserted.*, Deleted.*;
```</s>
|
<s>[INST]Hi All,
Hope you are doing well!...I am trying to find the sum of sales by ID and returning only the max of the name as there are multiple names for a single ID..Please find the DDL for the input and the output tables..Can you please help me here..
Input table
Create table ##input
(ID int,
name varchar(50),
sales int)
insert into ##input values
('3051','Department of psychology ','382'),
('3051','psychology department of medicine','4087')
output table
create table ##output
(ID int,
name varchar(50),
sales int)
insert into ##output values
('3051','psychology department of medicine',4469')
Thanks,
Arun
[/INST];with mycte as (
select *
,max(sales) over(partition by ID) maxSales
, sum(sales) over(partition by ID) sumSales
from ##input
)
select ID,name,sumSales as sales
from mycte</s>
|
<s>[INST]Hi
How to move SQL server database to another drive? I tried before by making offline, move physical database file and make online again but it failed, please help
[/INST]I received a message that the destination path is not valid although I mapped the folder in the server and copied the bath exactly, please help
You cannot use mapped drives, because the drive mapping applies to you user only. SQL Server runs under a different user and does not see that mapping. You need to specify a UNC path like \\\\SERVER\Share\folder\db.mdf. However, putting database on network drives is not to recommend.
If you want to move the database to an instance on the physical server, BACKUP/RESTORE is the way to go. And again, you need to use a UNC path.</s>
|
<s>[INST]Is it possible to disable read/select access in SQL server while keeping write access to an account?
[/INST]Starting point is that a user has no permissions at all in the database. If you only want the user to be able to write data, you would do:
```
GRANT INSERT, UPDATE, DELETE ON tbl TO someuser
```
Rather than a table, you can also specify a schema (`SCHEMA::dbo`) or leave the ON clause to give permissions to all tables in the database.
If you already have granted the user permissions, start with removing those. This may include taking the user out of roles.
There is also a DENY command, but you can easily shoot yourself in the foot with that command, so avoid it as long as possible.</s>
|
<s>[INST]when a row was inserted into a table on SQL Server?
is it not Nassery date column available of each table
I have 400+ table in a database and
[/INST]If your table don't have a column for the INSERT timestamp, then you can not get the information.</s>
|
<s>[INST]Hi, I want to calculate weeks (70 years - 175 days) . I want to get result in weeks. How many weeks for (70 years - 175 days)? Thanks
[/INST]There is some interpretation in your request. What do you define to be a week - 7 days, day of week to day of week, etc? Note that leap years could impact this calculation so which years would be important as well.
sql
DECLARE @startDate DATE = GETDATE()
DECLARE @endDate DATE = DATEADD(day, -175, DATEADD(year, 70, @startDate))
SELECT DATEDIFF(week, @startDate, @endDate)</s>
|
<s>[INST]I have a Main table that contains a field 'WONum'. A similarly named filed exists in two other tables. Those two other tables also contain the filed that I want to JOIN or UNION with my main table. That field is named 'WOQty'. So what I need is to JOIN my Main table with the WOQty from either of the other tables. Is that a JOIN or a UNION or something else entirely?[/INST]from another forum helped me with this query:
SELECT mt.BusinessUnit, mt.PartNum, mt.WONum, mt.TransDate, mt.TransQty, ISNULL(ot1.WOQty, ot2.WOQty) AS WOQty
FROM tblJDEWOData2 AS mt LEFT OUTER JOIN
tblWONumWOQty AS ot1 ON ot1.WONum = mt.WONum LEFT OUTER JOIN
tblHistory AS ot2 ON ot1.WONum IS NULL AND ot2.WONum = mt.WONum</s>
|
<s>[INST]I am running windows 11 pro. When I start SSMS, then I get 'cannot start application (0xc000007b); click OK to close the application'. I have already tried several solutions: be sure that I have the latest updates, uninstall and reinstall ssms, directx, .net is installed properly, restart PC, running as admin, running in compatiblity mode.
Ssms is the only app with this problem and it is also the first time that I start it in windows 11.
Does someone have the same problem or have advice what I can do to get it back running?[/INST]repairing Visual C++ Redistributable was enough to get it working.</s>
|
<s>[INST]Hi.
I would like to set User permission to achieve this goal: Deny see View definition (cannot see in Design, Alter view etc.) but see view in "Views list" in MSSMS. (Critical views is created by their own schema.) It is possible?[/INST]Your post is not clear, but keep in mind that by default users have no permissions at all, so there is normally not able no need for DENY.
If you only want the users to be able to access views in a certain schema, and that schema only has these views, you can grant SELECT permission on that schema. If you only want them to be able to SELECT on the views, but not see the view DEFINITION, you do need to DENY them VIEW DEFINITION on the schema. But then will not be able to see them in the views list either.</s>
|
<s>[INST]We are on - Microsoft SQL Server 2019 (RTM-CU9) (KB5000642) - 15.0.4102.2 (X64) Jan 25 2021 20:16:12 Copyright (C) 2019 Microsoft Corporation Enterprise Edition: Core-based Licensing (64-bit) on Windows Server 2019 Standard 10.0 (Build 17763: ) (Hypervisor)
Configured Always Encryption successfully on the DB server. As part of testing, we removed the cert from the windows cert store and ran the select query with the "Column Encryption Setting=enabled" setting, the query is throwing an error in the message as expected but the query keeps running until I kill it. This is happening in the DB server and from other servers too. Has anyone seen this issue before? If yes, what was the resolution? I am only running a select * and the default select top 1000 rows queries. Nothing fancy.Thanks in Advance![/INST]Unable to submit my Answer, so posting it here - This was happening because we had symmetric Key Column level Encryption on the same table. We had multiple Symmetric keys, certs from previous testing. Once we removed all of those, the above issue disappeared. I am not sure what the old Symmetric keys had to do with the above issue as it was on another column on the same table but cleaning them up it resolved it.</s>
|
<s>[INST]Hi,
I'm curious of the PK choice from MS in this type of table system. "stream_id" is [uniqueidentifier] but it's not the primary key... it is "path_locato"r which is a [hierarchyid].
Now inserting a record via t-sql and having the need to create a support table with the reference ID of the record, I would be inclined to use "stream_id", even if it is not the PK. Up until now, I've never had any problems.
What do you recommend?
Thank you, Alen[/INST]The system-defined FileTable schema includes a non-clustered primary key and two non-clustered unique constraiants. Any of these will uniquely identify a file table row:
- primary key constraint (non-clustered): path_locator (hierarchyid)
- unique constraint (non-clustered): stream_id (uniqueidentifier)
- unique constraint (non-clustered): parent_path_locator (hierarchyid), name (nvarchar(255))
The main advantage of storing `stream_id` in your support table for the file table row locator (and perhaps foreign key) is that it's narrowest of these candidate keys. I suggest `stream_id` for most use cases.</s>
|
<s>[INST]I have a query that uses a window function. The query runs fine. However, I want the result of my Revenue field to be formatted as currency. Tring to wrap the calc in a FORMAT function throws an error that "FORMAT" is not a valid window function. In the query below, how can I get my Revenue field to be formatted as currency?
```sql
select
Accountid,transdatelocal,
count(*) over(partition by transdatelocal) as cnt,
sum(DeltaCash) over(partition by transdatelocal) as Revenue
from TransDaily t where t.TransType = 'Result' and accountid in (109046382,108489070,115436142)
group by accountid,transdatelocal
order by accountid,transdatelocal
```
Thanks.
[/INST]Probably it was used incorrectly. Show the problematic query and try this:
SQL
select . . .
format(sum(DeltaCash) over(partition by transdatelocal), 'C') as Revenue</s>
|
<s>[INST]HI All - Below is my current Query:
The query runs daily now and appends the data into the Table1 but the problem is if the query runs on the same day twice or thrice it should truncate the data loaded on the same day.
Lets say the query ran today at 8 AM and it inserted data into Table1 with the SnapShotDatetime of 03/22/2022 8: 00 AM
But if the user wants us to re-run the query again at 1pm, it should truncate the data loaded ONLY on same day ( 8 AM) and then run the query and load the latest data at 1 pm. Similarly if the query/job runs at 10 pm then it should the 1 pm data..
Could you please help on how to do this in the query and create the final stored procedure so i can set it up as a SQL agent job.
Thank you
```tsql
Declare @Snapshot DATETIME = GETDATE()
SELECT column1, column2, column3, column4, column5, column6
,SnapShotDatetime
FROM [USDW].[dbo].[Table1]
INSERT INTO [USDW].[dbo].[Table1] (column1, column2, column3, column4, column5, column6
,SnapShotDatetime)
Select column1, column2, column3, column4, column5, column6
,@Snapshot
from OPENQUERY ( Linkedserver, 'Select * from LinkedTable')
```
[/INST]](/users/na/?userid=89c36154-0579-49d8-b331-26cb6342b7b5)
If I understand correctly, you want the query to be able to clear data from earlier in the same day and insert the latest data every time you run it.
You can add a delete statement before inserting data to clear data from earlier in the same day.
Just like this:
```sql
Declare @Snapshot DATETIME = GETDATE()
SELECT column1, column2, column3, column4, column5, column6
,SnapShotDatetime
FROM [USDW].[dbo].[Table1]
delete from [USDW].[dbo].[Table1]
where convert(char(10),SnapShotDatetime,111) = convert(char(10),@Snapshot,111);
INSERT INTO [USDW].[dbo].[Table1] (column1, column2, column3, column4, column5, column6
,SnapShotDatetime)
Select column1, column2, column3, column4, column5, column6,@Snapshot
from OPENQUERY ( Linkedserver, 'Select * from LinkedTable')
```</s>
|
<s>[INST]Hi All,
Sometimes just by updating stats with full scan on the tables involved in the poorly performing query would fix the problem.
How does that magic happen and why many people suggest to just go for updating statistics rather than rebuilding the indexes in certain scenarios ? is that because the rebuild operation is expensive in terms of I/O and the amount of transaction is generated? what is the logic behind that? Does the trick works for both smaller and big tables as well or does it work in only certain scenario's where data is not changing quite often?
Thanks,
Sam
[/INST]UPDATE STATISTICS takes up less resources, since it only reads data, and the only thing it writes is the the histogramme steps. Rebuilding the index means that all data for the index is copied from one place in the database to another. And since it reads all data, it updates the statistics with FULLSCAN while it's at it. It's a cheap by-product.
As for the parameters to IndexOptimize, they seem OK. I would have read Ola's documentation more closely to verify. But so could you.
By the way, I took the liberty to convert your Answers to Comments. Answers are for Answers to the original Question and not for followup questions. As the original poster, you would only post an Answer if you find the answer to your original Question yourself.</s>
|
<s>[INST]Hello I'm trying to change the owner of an active SQL 2014 DB using:
ALTER AUTHORIZATION ON DATABASE::[TargetDB] TO LoginNameOwner;
When I run it it seems to hang and notice causes Blocking so I cancel above statement.
While running above there are Sessions that are in the Suspended, Running, Runnable statuses.
Is it correct to say that you can't run this statement while it's in some other state than Sleeping?
Thanks in advance.[/INST]msft
Sounds like changing the owner the DB does need to be inactive/SLEEPING mode only?</s>
|
<s>[INST]
```tsql
i have many tables and i must join it
the first:
select
iek_actionid,
iek_productid
from iek_action_productid
then this table join to
select
productid
from product
productid=iek_productid
then this table must be join with this table by "iek_actionid"
select
iek_actionid,
iek_account_id
from iek_action_partner_id
also by "iek_actionid"
must be joined to this one
Select
iek_actionid,
iek_promotion_typeid
from iek_action
after by "iek_actionid"
with tables
1
select
iek_actionid,
accountid
from iek_action_customer
2
select
iek_actionid,
accountid
from iek_action_customer
3
select
iek_actionid,
iek_target_client_group_id
from iek_action_targetclientgroup
```
I can join them individually, but that would be cumbersome. What is the easiest way to make an inner join of the specified tables. Thanks for any of your help.
[/INST]What is the best way to join them all depends on the result you want. Since all I know is some table and column names and I know nothing about the data and what the result you desire I cannot give you a query.
But when you join tables, you use the JOIN operator. For instance:
```sql
SELECT P.ProductName, P.ProductID, A.ActionID, ActionName
FROM Product P
JOIN ProductActions PA ON P.ProductID = PA.ProductID
JOIN Actions A ON A.ActionID = PA.ActionID
```
If you want more detailed help for your scenario, I would recommend that you post the CREATE TABLE statements for your tables, INSERT statements with sample data, and the desired result given the sample.</s>
|
<s>[INST]Hi all,
we have installed on SQL 2019 Developer Edition the Polybase features.
After that, we've created an external data source towards our Mongodb server, where we've stored lots of big tables containing applicative logs.
*CREATE DATABASE SCOPED CREDENTIAL mongo_creds WITH IDENTITY = 'XXXXXXXXXXXX', Secret = 'XXXXX!';
go
CREATE EXTERNAL DATA SOURCE MongoDBSource
WITH (LOCATION = 'mongodb://nnn.nnn.nnn.nn:27017',
CREDENTIAL = mongo_creds,
CONNECTION_OPTIONS = 'ssl=false;')
go
CREATE EXTERNAL TABLE...
*
It works, but we have experienced many performance problems in querying large tables (about 50-100 GB) on Mongodb, as soon as we try to query with conditions.
The "select top 100 *" is lightning fast, but running a query "...where field = 15" can take more than twenty minutes. On any table, despite the same query on Mongo lasts just a second.
In addition, we have noticed that when we run the query from SQL, the system tries to "download" the entire table to the swap files on the Windows machine ( C: \ Windows \ ServiceProfiles \ NetworkService \ AppData \ Local \ Temp)...
Anyone have any idea what we could try to speed up queries and avoid this kind of swap?
Thanks in advance.
Luca
[/INST]we created indexes and they're very useful when you run the query on Mongodb... Running queries from Sql Server have no benefit at all.
I think the point is what Sql seems to do every time we run a query: uses the swap directory to download the dataset to be queried...
If I check the sys.external_data_sources table, we defined correctly the pushdown parameter (= ON), so the query activity should be beared by the Mongo dataserver ...
...I just found on the Microsoft manuals that pushdown vs Mongodb community dataserver is not active in many situations:
> If the join can be done at the external data source, this reduces the amount of data movement and improves the query's performance. Without join pushdown, the data from the tables to be joined must be brought locally into tempdb, then joined.
Maybe this could be the answer...</s>
|
<s>[INST]From SQL Server management studio, I created a linked server which is my AWS Athena awsdatacatalog. Now I am able to query my Athena external tables from SSMS.
Is it possible to move the data (of external tables) from "Linked Servers" to the actual "Databases"? If yes, please let me know the steps.[/INST]tried and was successful. Planning to make it a scheduled script like a nightly load.</s>
|
<s>[INST]I see that I'm able to enable and disable instance file initialization using "Instant File Initialization" item under the "Advanced" tab using SQL Server Configuration Manager. I have SQL Server 2019 installed. What I'm trying to figure out in what version of SQL Server did this become available. I am wonder if was SQL Server 2016, since that was the version that let you enable instant file initialization during the installation of SQL Server. Was it SQL Server 2016 when the added that options to configuration manager? If not when did Microsoft add this feature?[/INST]nice hearing from you. If I understand your post you tested the different versions of SQL Server Configuration Manager (SSCM) and found that only the SQL Server 2019 version support enabling/disabling Instant File Initialization on the "Advanced" tab. In all other versions you need to use secpol.msc to enable instant file initialization after SQL Server has been installed. Of course starting with SQL Server 2016 you can also set up instant file initialization during the installation process. Please confirm that is what you found during testing of SSCM.</s>
|
<s>[INST]Hi guys,
There is a reconciliation between the two systems at certain periods, but this reconciliation is compared with the result obtained by querying the database and excel file. To automate this manual process, I insert the incoming excel into a table in the database with **SQL Bulk Copy**. I will then compare these two tables.
The **GameConfirmResponses** table has all the transactions. (It may make more sense to filter by the date range to be reconciled.) **RazerReconciliation** is the table that I populated from excel. There might be transactions that the GameConfirmResponses table has and the RazerReconciliation table does not and vice versa so somehow I need to check that scenario too in the SQL query.
I hope I was able to explain my problem.
```sql
Select ReferenceNo
From RazerReconciliation A
Where NOT EXISTS
( select referenceId from GameConfirmResponses B
Where A.ReferenceNo = B.referenceId
);
```
[/INST]How about?
sql
Select ReferenceNo, 'In Razer' as Type From RazerReconciliation A
Where NOT EXISTS
( select referenceId from GameConfirmResponses B Where A.ReferenceNo = B.referenceId )
UNION ALL
select referenceId, 'In Game' as Type from GameConfirmResponses a
where not exists (select 1 from
RazerReconciliation b WHERE a.ReferenceID = b.ReferenceNo)
;</s>
|
<s>[INST]I am attempting to install a SQL 2019 server on my local computer. At the last step I receive the following error:
Error installing Microsoft ODBC Driver for SQL Server
A previous installation required a reboot of the machine for changes to take effect. To proceed, restart your computer and then run Setup again.
Error code: -2147483648
I have rebooted my computer as well as reattempted the setup process but continue to receive the same error. Does anybody know what my next troubleshooting steps should be or how to solve this issue?[/INST]It turns out I actually had the wrong ODBC driver installed (I had 13 instead of 17) so it appears the install has worked. However, if I run into another issue later I'll be sure to check out this resource.</s>
|
<s>[INST]**Any assistance with merging the following two select queries would be greatly appreciated.**
- The first query returns 1000 rows
- The second query returns 1000 rows.
- RSV.ResourceID is the primary key
- RSV.ResourceID by itself outputs 14,000 rows.
**The end goal is to output all 14,000 rows for RSV.ResourceID and have it include a column with results for GBU.BrowserName0 and a column with results for GLD.Size0.**
Select RSV.ResourceID, GBU.BrowserName0
From (
select ResourceID,
max(GBU.UsagePercentage0) as UsagePercentage0
from
v_GS_BROWSER_USAGE GBU
WHERE
GBU.UsagePercentage0 > 0
group by ResourceID)
as s
INNER JOIN v_GS_BROWSER_USAGE GBU on (GBU.Resourceid = s.ResourceID and GBU.UsagePercentage0 = s.UsagePercentage0)
RIGHT OUTER JOIN v_R_System_Valid RSV on GBU.Resourceid = RSV.ResourceID
**___________________________________________**
Select RSV.ResourceID, GLD.Size0
From (select ResourceID,
max(gld.deviceid0) as deviceid0
from
v_GS_LOGICAL_DISK GLD
WHERE gld.deviceid0='C:'
group by ResourceID)
as d
INNER JOIN v_GS_LOGICAL_DISK GLD on (GLD.Resourceid = d.ResourceID and GLD.deviceid0 = d.deviceid0)
RIGHT OUTER JOIN v_R_System_Valid RSV on GLD.ResourceID = RSV.ResourceID
[/INST]I was able to work through this using an Outer Apply.</s>
|
<s>[INST]I have a database of an application restored in a environment that runs a newer application version than the database version.
The databases contain hundrends of tables, most of which are same.
I know the application expect to find additional fields and maybe tables not existed in the database early version.
I use SQL server version 13.0.5865.1
**How** I can keep the original/empty environment database schema with old version database data?
[/INST]Well after import the old backup with the data - run Syncronize database from Visual Studio Dynamics 365 menu and its work :)</s>
|
<s>[INST]Msg 4305, Level 16, State 1, Line 47
The log in this backup set begins at LSN 33000000048000001, which is too recent to apply to the database. An earlier log backup that includes LSN 33000000044800001 can be restored.
Msg 3013, Level 16, State 1, Line 47
RESTORE LOG is terminating abnormally.
Hello team,
I was trying to do the mirroring between my primary server and mirror server but the thing is i am enable to create it.
i created took a full backup and transition log backup, and i restore databse over mirror server but when i was trying to restore transition log file i am getting the above error which related to lSN.
use msdb
--select *from log_shipping_monitor_primary
select
BS.database_name,
BF.physical_device_name,
BS.first_lsn,
BS.last_lsn,
BS.Checkpoint_lsn,
BS.backup_start_date,
BS.backup_finish_date
from backupset BS, backupmediafamily BF
where
BS.media_set_id = BF.media_set_id
and BS.database_name='xxxxxxxxx'
i found the number as well by using above command i saw the gap but the thing is all file backups are in .BAK extension and i try to restore the LSN Number shown into the error but its giving me same error i dont know what to do now i tryed many ways but still the same error.
I tryed with another database which dont set for automatic backup and i am able to do the mirroring but with other dtabase who set for autmatic backup are giving me LSN error.
[/INST]from your description
> which dont set for automatic backup
I suggest that on the other server - where you have the problem - some automatism is enabled for backups... that get in between your full and your first log backup.
Recommendation:
Option1: disable the automatism
Option2: reconfigure automatism to take a "CopyOnly" FULL, so it doesn't destroy your backup chain.
I hope my answer is helpful to you,
Your</s>
|
<s>[INST]I have a Main table that is joined to a second Table via the Main tables primaryKey. Within the second table there are multiple columns but 5 of these columns all reference the same lookup table. I have an SQL Query that returns all the relevant records from the Main table and the Second table with the exception of the 5 columns linked to one Lookup table. How can i return this data also.
Thank you for your assistance.[/INST]](/users/na/?userid=c84d79f7-ee2c-45af-adc2-a7a09ce7e136)
Not sure what you actually want, but If I understood right, you need to use `Join` twice.
Try something like this:
```sql
SELECT M.<column list>,S.<column list>,L.<column list>
FROM MainTable M JOIN SecondTable S ON M.primaryKey=S.ForeignKey
JOIN LookUpTable L ON M.primaryKey=L.ForeignKey
```</s>
|
<s>[INST]Hello!
I have encountered some problems with query.
I have three tables, each of which has a column.
They look like this.
table1table2table3column1column2column3SS5FSS5FSS8DSS8DQA8AKH6CKH6CBC5ASA6SQA8AKH6CIY1KSA6SSA6SQA8ALJ6VBC5AIY1KBC5A
I need a query to find the data in table1, but not in table2 and table3.
For example, in the example data given above, I want to get 'LJ6V' in table1.
Thank you in advance.
[/INST]](/users/na/?userid=5628d4c6-7d6d-4f1a-9646-c593af4070d2)
If I understand correctly, you can try this query.
```sql
create table table1(column1 varchar(max));
create table table2(column2 varchar(max));
create table table3(column3 varchar(max));
insert into table1 values
('SS5F'),('SS8D'),('KH6C'),('QA8A'),('SA6S'),('LJ6V'),('IY1K'),('BC5A');
insert into table2 values
('SS5F'),('QA8A'),('BC5A'),('KH6C'),('SA6S');
insert into table3 values
('SS8D'),('KH6C'),('SA6S'),('IY1K'),('QA8A'),('BC5A');
;with CTE as(
select column2 as uni from table2
union
select column3 from table3)
select column1 as result from table1 as t1
where not exists (select uni from CTE as t2 where t1.column1 = t2.uni);
```</s>
|
<s>[INST]Experts,
I have one VM with MS-SQL hosted on it having 24 databases on it each one connected to their applications respectively. Based on requirement have to segregate the 24 databases onto 3 different SQL Instances on 3 different VM's , 8 each. Is there a way or formula to calculate the compute capacity for the 3 VM's(CPU and Memory) to avoid contention , as different databases have different workloads[/INST]Taking into consideration How to analyze SQL Server database performance using T-SQL for CPU, Memory and disk script output , some more guidance :
1. For the Query : CPU – Identify workload -> can we say that the database MES_DB2_PROD is utilizing the max CPU and hence the max CPU is to be aligned to the VM where this database is hosted. On a very high level say the initial 1 VM has 12 vcores , the maximum core VM would be the one having MES_DB2_PROD database.
2. For the Query : Buffer pool memory management -> The memory utilized defined by the BufferPageCnt. Can we sum up the BufferPageCnt and divide it on the basis of databases to calculate the memory utilized on a high level.
3. Disk I/O Management : Defines the disk utilization , but is there a way to calculate the IO's required to calculate the requirement</s>
|
<s>[INST]Right now our company databases are set to default "READ COMMITTED".
When I run a T-SQL update script, I'd like to tighten up transaction updates. I'm interested in the SNAPSHOT isolation level, but this is a database-level change.
How will it impact others users and their work? I only want to protect my script and my updates, but not necessarily other sessions with read/update/write.
I'm new at this. Special thanks to Erland for helping me think through this![/INST]Although the SNAPSHOT isolation level is controlled at the session level, it is permitted only when the ALLOW_*SNAPSHOT*_ISOLATION database option is turned on. Once the database option is turned on, additional overhead is incurred of additional storage space (14 bytes per row) plus increased space/usage in tempdb for the row version store. The overhead may be offset by the concurrency benefits of reduced locking/blocking/deadlocking, depending on your workload.
> How will it impact others users and their work? I only want to protect my script and my updates, but not necessarily other sessions with read/update/write.
As I understand your other question, you run a SELECT query and then iterate over the results to update rows. Assuming your script is running in a SNAPSHSOT isolation level transaction and the other users are using default READ_COMMITTED (without RCSI), your SELECT query will return rows as they existed at the time the SELECT query started. The query will 1) not return rows inserted during SELECT query execution, 2) return the before value of rows updated during query execution, and return rows deleted during query execution.
If you attempt to UPDATE a row which has been modified or deleted by another session, you'll get the dreaded update conflict error below and you can simply rerun your script.
> Snapshot isolation transaction aborted due to update conflict. You cannot use snapshot isolation to access table 'dbo.YourTable' directly or indirectly in database 'Example' to update, delete, or insert the row that has been modified or deleted by another transaction. Retry the transaction or change the isolation level for the update/delete statement.
Other READ_COMMITTED sessions that attempt to access a row modified by your transaction will block until your transaction commits because normal locking behavior applies. The impact to these other sessions will be insignificant if the blocking duration is short (i.e. your transactional script runs quickly). If it runs a long time and you've already optimized the query/indexes, you can mitigate impact to other sessions by processing in multiple smaller batches (e.g. a TOP clause in the select query) instead of one large transaction.</s>
|
<s>[INST]Hi,
We have replication set-up on sql server 2014. By default non-clustered indexes are not replicated. We are thinking to enable the same from the publisher properties.
Is it safe to perform this action keeping database is online ?[/INST]](/users/na/?userid=70a74c92-a258-4ae2-b5b5-6523e0c4ece1),
Yes, just set “Copy no clustered indexes” in the articles property to “true”, this will cause all no clustered indexes on the publisher to be included in the snapshot for delivery on the Subscribers. But additional subscriber non-clustered indexes don’t come without a cost. Like all SQL Server indexes, there is additional overhead for INSERT, UPDATE, DELETE, additional locks\blocking, and index maintenance to consider. If all indexes are not needed, alternatively, you can create selective indexes directly on a subscriber. It reduces administrative overhead to change the option directly in the replication settings for the article.</s>
|
<s>[INST]Hello all. I'm trying to get YTD and MTD for two different types of rows (based off a column in the table) from a TimeEntries table. I've tried the other solutions I've found on here, but nothing has worked.
```
CREATE TABLE [TimeEntries] (
Id int IDENTITY(1,1) PRIMARY KEY,
TransactionDate date,
BillableHours money,
BillableFlag nvarchar(2)
)
INSERT INTO [TimeEntries] (TransactionDate, BillableHours, BillableFlag)
VALUES ('2023-05-01', 2.00, 'B'),
('2023-01-05', 3.00, 'N'),
('2023-05-05', 4.00, 'B'),
('2023-02-06', 5.00, 'N'),
('2023-05-01', 20.00, 'B'),
('2023-01-05', 30.00, 'N'),
('2023-02-05', 40.00, 'B'),
('2023-02-06', 50.00, 'B');
Select
MTD = Sum(Case When datediff(month, current_timestamp, a.TransactionDate) = 0 Then a.BillableHours Else 0 End),
YTD = Sum(Case When datediff(year, current_timestamp, a.TransactionDate) = 0 Then a.BillableHours Else 0 End)
From [TimeEntries] a
where a.BillableFlag = 'b'
Group by a.TransactionDate, a.BillableHours
GO
Select
MTD = Sum(Case When datediff(month, current_timestamp, a.TransactionDate) = 0 Then a.BillableHours Else 0 End),
YTD = Sum(Case When datediff(year, current_timestamp, a.TransactionDate) = 0 Then a.BillableHours Else 0 End)
From [TimeEntries] a
where a.BillableFlag = 'n'
Group by a.TransactionDate, a.BillableHours
GO
DECLARE @billableHoursWorkedMTD money
DECLARE @billableHoursWorkedYTD money
DECLARE @nonbillableHoursWorkedMTD money
DECLARE @nonbillableHoursWorkedYTD money
SET @billableHoursWorkedMTD = (SELECT sum(BillableHours) FROM [TimeEntries] where BillableFlag = 'B' AND TransactionDate BETWEEN dateadd(month, datediff(month, 0, current_timestamp), 0) AND GETDATE())
SET @billableHoursWorkedYTD = (SELECT sum(BillableHours) FROM [TimeEntries] where BillableFlag = 'B' AND TransactionDate BETWEEN dateadd(year, datediff(year, 0, current_timestamp), 0) AND GETDATE())
SET @nonbillableHoursWorkedMTD = (SELECT sum(BillableHours) FROM [TimeEntries] where BillableFlag = 'N' AND TransactionDate BETWEEN dateadd(month, datediff(month, 0, current_timestamp), 0) AND GETDATE())
SET @nonbillableHoursWorkedYTD = (SELECT sum(BillableHours) FROM [TimeEntries] where BillableFlag = 'N' AND TransactionDate BETWEEN dateadd(year, datediff(year, 0, current_timestamp), 0) AND GETDATE())
Select @billableHoursWorkedMTD as 'MTD', @billableHoursWorkedYTD as 'YTD', @nonbillableHoursWorkedMTD as 'MTD', @nonbillableHoursWorkedYTD as 'YTD'
```
```
```
This results in a Billable (where billableFlag = 'B') dataset like so:
> 2.00 2.00
> 4.00 4.00
> 20.00 20.00
> 0.00 40.00
> 0.00 50.00
and a Non-Billable (where billableFlag = 'N') dataset like so:
> 0.00 3.00
> 0.00 5.00
> 0.00 30.00
I'm wanting a dataset like so:
> 26.00 116.00
> 0.00 38.00
where the first row is billableFlag = 'b' and the second row is billableFlag = 'n'.
The variables at the end are there as an example for each cell of data. Any help is appreciated.
[/INST]](/users/na/?userid=a1877d11-2f3a-4865-8c14-228701c32e8b)
> where the first row is billableFlag = 'b' and the second row is billableFlag = 'n'.
How about using UNION like this:
```sql
;WITH CTE AS
(
Select MTD = Sum(Case When datediff(month, current_timestamp, a.TransactionDate) = 0 Then a.BillableHours Else 0 End),
YTD = Sum(Case When datediff(year, current_timestamp, a.TransactionDate) = 0 Then a.BillableHours Else 0 End),
'b' as billableFlag
From [TimeEntries] a
Where a.BillableFlag = 'b'
UNION
Select MTD = Sum(Case When datediff(month, current_timestamp, a.TransactionDate) = 0 Then a.BillableHours Else 0 End),
YTD = Sum(Case When datediff(year, current_timestamp, a.TransactionDate) = 0 Then a.BillableHours Else 0 End) ,
'n' as billableFlag
From [TimeEntries] a
Where a.BillableFlag = 'n'
)
Select MTD,YTD
From CTE
Order by billableFlag
```</s>
|
<s>[INST]I am trying to connect a JDBC connection to SQL Server, and uppon digging it appears that I need to enable the option "TCP/IP" in the "SQL Server Network Configuration" section of the program Sql Server Configuration Manager. What was unexpected to me was that the dropdown has no options for either enable or disable, it is just a blank dropdown and I can not enter my own text.
I have already tried running the config manager as admin, and it is a locally ran database so I should be the owner of the said database.[/INST]The issue was I was running the executable found inside of System32, however I needed to run the exe found inside of C:\Windows\SysWOW64</s>
|
<s>[INST]I am configuring and testing mssql server 2019 on Redhat 7.9 and have the following issue:
When importing the schema for mysql there is a nas table entry, however, for mssql the nas table entry is not there.
I have converted the mysql code into mssql code to create a nas table and can enter data into the table via either command line or "Heidi SQL". However, the issue occurs when I run the radtest command. If I use the following credentials as an example:
nas table:
Server = <my freeradius address>
Shortname = <Whatever, does not really matter>
Secret = anything
radcheck table:
User = clive
Attribute = Cleartext-Password
Value = test123
OP = :=
Now I run the radtest statement:
radtest clive test123 localhost 1812 anything --- This does not even contact the database as I see absolutely nothing being returned. However, if I type the following:
radtest clive test123 localhost 1 testing123 ---- This all works and I get the access accept. The returned response shows the local server as the nas address but that could be because I used localhost.
This suggests that the radcheck is being returned fine but the "nas" table does not look like it is being read at all.
There appears to be no documentation surrounding this issue and hoping someone may have seen this before and knows a workaround.
Is the "nas" table actually supported given that it is missing from the mssql schema for freeradius?
Any help appreciated. Many thanks.[/INST]I believe I have found the resolution to this issue and was about to update when your answer came through.
There is a file called sql located in /etc/raddb/mods-available/sql
In that file there is a line that states "read_clients = yes" .... as a default this line is commented out and the "clients" it mentions are taken from the "nas" table. I uncommented that line and restarted the mssql-server and now the nas table is being read correctly.</s>
|
<s>[INST]have 4 tables..1,2,3,4..need to
join tables 1 & 2
union all
join tables 3 & 4
return just one count from the union
[/INST]Providing sample tables and data and the result you would want from that sample data would make your question more clear, but something like
sql
;With cte
As
(Select <column list>
From Table1
Inner Join Table2 On <join condition>
Union All
Select <column list>
From Table3
Inner Join Table4 On <join condition>)
Select Count(*) From cte;</s>
|
<s>[INST]Try pivot query to calculate the total quantity and total price amount for each order ID for the four quarters.
Tried as follows, but the result is not right which should be only one line per order ID. The code is as follows:
```
select * from
(
select OederID,units,Price
,'Q'+ cast(datepart(Q,Order_date)as varchar) + '_Qty' as col1
,'Q'+ cast(datepart(Q,Order_date)as varchar) + '_Total' as col2
from #test_table
) as a
pivot ( sum(units) for col1 in ([Q1_Qty],[Q2_Qty],[Q3_Qty],[Q4_Qty]) ) as pvt1
pivot ( sum(Price) for col2 in ([Q1_Total],[Q2_Total],[Q3_Total],[Q4_Total])) as pvt2
```
Please help, thanks in advance!
[/INST]microsoft.com/en-us/users/na/?userid=772119a2-1f56-46b7-abb1-4ad3b69358cc)
Don't know your table details, but you might try this code using aggregate function along with CASE WHEN instead of PIVOT.
```sql
SELECT OederID,
SUM(CASE WHEN DATEPART(Q,Order_date)=1 THEN Units END) AS [2023_Q1_Qty],
SUM(CASE WHEN DATEPART(Q,Order_date)=1 THEN Price END) AS [2023_Q1_Total],
SUM(CASE WHEN DATEPART(Q,Order_date)=2 THEN Units END) AS [2023_Q2_Qty],
SUM(CASE WHEN DATEPART(Q,Order_date)=2 THEN Price END) AS [2023_Q2_Total],
SUM(CASE WHEN DATEPART(Q,Order_date)=3 THEN Units END) AS [2023_Q3_Qty],
SUM(CASE WHEN DATEPART(Q,Order_date)=3 THEN Price END) AS [2023_Q3_Total],
SUM(CASE WHEN DATEPART(Q,Order_date)=4 THEN Units END) AS [2023_Q4_Qty],
SUM(CASE WHEN DATEPART(Q,Order_date)=4 THEN Price END) AS [2023_Q4_Total]
FROM #test_table
WHERE YEAR(Order_date)=2023
GROUP BY OederID
```</s>
|
<s>[INST]Hello I have a Project Server 2013 with SQL Server 2014 environment and lately the ProjectWebApp database grows up to 50-100 GB every night. Reviewing I found that PROCEDURE pub.MSP_WEB_SP_SEC_PSMODE_PERM_SYNC_DeleteAllOldPermissionStates is the culprit, and table MSP_WEB_SECURITY_PSMODE_PERMISSION_SYNC_STATES grows too from less 1 gb to 51 gb. We currently have more than 2000 projects and more than 1000 users (active and inactive) in Project Server but I do not find it normal for the log to grow so much. Additionally, database recovery model was changed to Simple and the growth of the log was the same. I appreciate if someone can guide me to understand why this happens.[/INST]Your advice helped a little in terms of understanding the problem in a general sense.
But I found a very cardinal and dangerous solution - I made a drop and create table inside MS SQL Studio at my own risk. But I made a backup of this database beforehand. So far everything looks good. But this table stopped filling, it stopped having any data. But my site still works without errors. Stopped getting error notifications...
I don't recommend this method to anyone, but it "helped" me.
Still, it is worth discussing this method with MS Project 2013 specialists.</s>
|
<s>[INST]Hello
I've got a table, that I need to import approx 400 million records. I've read that it's quicker to drop constraints/Indexes, import the data and recreate the constraints/Indexes. Dropping the constraint is straight forward, but I'm not sure about recreating it.
When /I script out the table, the constraint is
CONSTRAINT [PK_TableTest] PRIMARY KEY CLUSTERED ( [ColName] ASC ) )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
How do I script the code above as a Create Index/Constraint?
Many thanks
[/INST]it is correct that you if you want to large volumes of data, you can gain quite some speed by disabling indexes and constraints and re-enable them afterwards.
But there is one exception: the clustered index. My experience is that is faster to have the clustered index in place when you do the load. And you example is exactly that: a clustered index.
Else, to disable all CHECK and FOREIGN KEY constraints is one single statement:
```sql
ALTER TABLE tbl NOCHECK CONSTRAINT ALL
```
To re-enable them, you run:
```sql
ALTER TABLE tbl WITH CHECK CHECK CONSTRAINT ALL
```
And, no, there is no typo, but it should be CHECK twice.
To disable an index, you say:
```sql
ALTER INDEX ix ON tbl DISABLE
```
You need to run this once for all non-clustered indexes: Whether they also are constraints does not matter.
To re-enable them, you can run
```sql
ALTER INDEX ix ON tbl REBUILD
```
for each index. You can also re-enable all in a single command:
```sql
ALTER INDEX ALL ON tbl REBUILD
```
But this will also rebuild the clustered index, so this will take longer time.</s>
|
<s>[INST]Hi
We have a select query on a table. Based on if the query returns any rows, how can we update a column in a second table?
Thanks
Regards
[/INST]you can do something like this:
```SQL
if exists( select * from Table1 ) -- if the first query returns any row
update Table2 -- update a column in the second table
set SomeColumn = 'some value'
```
It depends on different aspects of your problem.</s>
|
<s>[INST]Hello,
I am using a software which updates a datetime column periodically in a SQL Server 2019 Database.
This software sometimes updates with an incorrect datetime value (eg '3262196-08-27 00:00:00') and generates a conversion error.
I have created an "INSTEAD OF UPDATE" trigger in order to check of this value before update and change it if needed.
When I issue an update statement with a correct value, I can see that the trigger fires correctly because of a message being printed during execution.
However, when I issue the problematic update statement, I get the conversion error and the message doesn't print, which leads me to believe that the trigger is not fired.
Is the datatype conversion checked before the trigger is fired ?
(i.e. update table set <datetime_field> = '3262196-08-27 00:00:00' where key = key
already produces a conversion to datetime)
How could I get the desired result, for instance changing this value to '2022-02-07 00:00:00' ?
Thank you for your help ![/INST]There is a possibility to save the show, although it's a little complicated.
You rename the table to something else. Then you create a view where you make the datetime columns into strings with the convert function. Then you add an INSTEAD OF trigger on the view which writes the data to the table.
But this also means that queries against this view will return strings instead of dates, and that certainly could have repercussions.</s>
|
<s>[INST]Dear All,
I have a table containing the following data. There are duplications in the left columns (sjcode, courseno, sjversion).
sjcodecoursenosjversiontraineridHELPHAD01B212HELPHAD01C21319HELPHAD01C2167HELPHAD01D1133HELPHAD01D1144I want to remove the duplication and keep an arbitrary value of **trainerid**.
**sjcode****courseno****sjversion****trainerid**HELPHAD01B212HELPHAD01C21319HELPHAD01D1144How to do it?
(By the way, I don't know how to remove the top left cell.)
[/INST]If you just want to remove the rows in a query but not from the table then use a distinct when selecting the rows and include the columns that you want unique.
DECLARE @table TABLE (sjcode VARCHAR(20), courseno VARCHAR(20), sjversion INT, trainerid INT)
INSERT INTO @table VALUES
('HELP', 'HAD01B', 2, 12),
('HELP', 'HAD01C', 2, 1319),
('HELP', 'HAD01C', 2, 167),
('HELP', 'HAD01D', 1, 133),
('HELP', 'HAD01D', 1, 144)
SELECT DISTINCT sjcode, courseno, sjversion FROM @table
Note that you can only include the columns you want to be unique here. To get to the rest of the columns you'll need to use this query in a larger query where you join back to the original table and that is where you'd determine what actual row (containing the trainerid) to select. You could do that using a subquery, CTE or by putting this query in a view. It depends on your needs.
An alternative approach is to group by the unique columns. This works better if you want to select the earliers or latest trainerid. But, as with the previous solution, if you want other columns then it will need to be done in a subquery, CTE or in a view.
SELECT sjcode, courseno, sjversion, MAX(trainerid) FROM @table GROUP BY sjcode, courseno, sjversion</s>
|
<s>[INST]I have a table called "Table1" which contains two columns.
ColA and ColB.
ColA values like ==> 100A,300B,200C,500A
ColB values like ==> 100A,300B,200C,500A,700D
Final Result value ==> "700D"
In what query have to use to find unmatched values from both columns...
[/INST]](/users/na/?userid=05028556-4001-0003-0000-000000000000)
Try this query.
```sql
;with T1 as(
SELECT substring(ColA,number,charindex(',',A.ColA + ',' ,number) - number ) as ColA
from Table1 A with (nolock),master..spt_values with (nolock)
where type = 'p' and substring(',' + A.ColA ,number,1) = ','
),T2 as(
SELECT substring(ColB,number,charindex(',',B.ColB + ',' ,number) - number ) as ColB
from Table1 B with (nolock),master..spt_values with (nolock)
where type = 'p' and substring(',' + B.ColB ,number,1) = ',')
select ColB as Mismatch from T2 as C
where not exists(select ColA from T1 as D where C.ColB =D.ColA);
```</s>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.