text stringlengths 209 10.7k |
|---|
<s>[INST]Listeners in AG for multiple databases
I have environment, where is one cluster with 2 nodes. In every node there are 4 Availability group each with one database and its own listener.
AG A - DB A - Listener A
AG B - DB B - Listener B
AG C - DB C - Listener C
Application uses Listener A.
There is situation where application needs to read view, that combines data from database A and database B. But database A has listener A and database B has listener B. So if application uses listener A, there can be situation where database B will be on different node as database A. And view will not work.
What is best solution for this situation?
- Group database A and B under one Availability group and one listener?
- Create second listener that will be same for database A and B?
- Keep databases on the same node? - this is really bad idea I believe.
Thanks.
[/INST]#NAME?</s> |
<s>[INST]Date Value Incorrect When Converting To Interger
Hi,
I am attempting to recreate a concat that I use in MS Excel, so I can use this in SQL. The concat consists of (First 3 letters of) Forename, Surname and DOB as a value.
I am getting slightly different results in SQL and I wonder if it is rounding the DOB value.
For example:
**John Smith 11/05/2010**
**EXCEL:**
=SUBSTITUTE(CONCATENATE(TRIM(M4),LEFT(TRIM(L4),3),VALUE(N4))," ","")
SmithJoh40309
**SQL:**
CONCAT (FAM_MEMBER.SURNAME, LEFT(FAM_MEMBER.FORENAME,3),CONVERT(INT,FAM_MEMBER.DATE_OF_BIRTH)) AS 'CONCAT',
SmithJoh40307
As you can see, its the DOB part which isnt quite right. Any advise on this, I would be very grateful! Thanks
[/INST]Both MS Excel and SQL Server stores dates as numeric values and calculate the date on the fly.
But both use different zero-bases, you see it when you convert numeric 0 to a date; then return different dates.</s> |
<s>[INST]multiple SQL collation on same machine
Hi,
Is it possible to install different collation for different SQL instances on same machine with same language.
like instance1 with Latin1_General_CP1_CI_AS
and
instance2 with Latin1_General_CI_AS[/INST]that is absolutely possible.
That collations are in the instance and mainly for the system databases => means that on an ideal base all your user databases have the same collation as your system databases.
Those database collations due not really rely on the system language.
So as you already wrote you have to install different instances on the same server if you have different collations. (technically it is possible to use different collation within one instance but it is not recommended)</s> |
<s>[INST]Compress Indexes
Hello, is it correct to say if I compress a Table as example:
ALTER TABLE [dbo].[Table_Items] REBUILD WITH (DATA_COMPRESSION=PAGE);
Afterwards I don't need to run compress script for it's Clustered Index since the Clustered Index is the table?
If yes, can anyone provide script to compress all Nonclustered Indexes within a SQL 2016 user DB (excluding Clustered Indexes if above is correct)?
Thanks in advance.[/INST]Afterwards I don't need to run compress script for it's Clustered Index since the Clustered Index is the table?
Yes.
> If yes, can anyone provide script to compress all Nonclustered Indexes within a SQL 2016 user DB (excluding Clustered Indexes if above is correct)?
To compress all indexes on a table do:
ALTER INDEX ALL ON tbl REBUILD WITH (DATA_COMPRESSION = PAGE)</s> |
<s>[INST]Trim my ID
Hi,
I have different lengths within a number that follow a similar pattern, but my substring doesn't work due this.
Some IDs are 5/123456 and other IDs are 5/00123456
Any idea how to can just get to the number of 123456 as my output, please?
[/INST]Since you are using SUBSTRING function, and I guess the result you could get is '123456', '00123456'.
If you want to get rid of the extra 0 in front of the number, there is a simple solution: Convert the data type of string from VARCHAR/NVARCHAR to INT/BIGINT, so that SQL Sever will automatically ignore the extra 0 in front of the number.
Check this:
Create Table #test (Number varchar(100))
Insert Into #test (Number) Values
('5/123456')
,('5/00123456')
,('5/0000123456')
SELECT CAST(SUBSTRING(Number,CHARINDEX('/',Number,1)+1,LEN(Number))AS BIGINT) New_Number
FROM #test
--Or
SELECT TRY_CAST(RIGHT(Number,LEN(Number)-CHARINDEX('/',Number,1)) AS BIGINT) New_Number
FROM #test</s> |
<s>[INST]Using SQL Server Management Studio
May I please ask, if using SQL Server Management Studio can work without having SQL Server installed in a development computer?
I have been trying to connect using SQL Server Management Studio but I keep getting error
"A network-related or instance-specific error occurred while establishing a connection to SQL Server"[/INST]you can use SSMS without having SQL Server installed locally. You can connect to any SQL Server instance you can find on the network.
You say that you want to connect to your production server from your development machine. I think you need to discuss how to do this with the DBA or your IT department. We don't know any details about your environment, so we cannot really help you with those details. However, it is not impossible that the network is configured in such a way that you cannot connect directly to the SQL Server instance from your development machine for security reasons.</s> |
<s>[INST]Is it possible to transfer tables and stored procedures to another database in Visual studio?
I discovered that when i added my database, I didn't use the standard to add it.
This is how I added my database:
I went to the server explorer and right-clicked on Data Connections.
Then I selected Add connection.
I then chose Microsoft SQL Server Database File (SqlClient) and
added the database file name and other details, I tested the connection and clicked OK
I should have used the Create New SQL Server Database option.
Now I have created a new database using the Create New SQL server Database option, is it possible to transfer my tables and stored procedures to this new database I created?[/INST]Visual Studio includes a schema compare feature (part of SSDT) which allows you to compare 2 databases and selectively apply differences to the target database.
From the main VS menu, select Tools-->SQL Server-->New Schema Comparison. Then select a source and target database connection (click browse if needed to create a new connection) and click Compare. You can then select differences to apply, including all objects for your use case.</s> |
<s>[INST]How to validate user if input formate no yyyy-MM-dd for created date ?
I work on sql server 2017 i need to validate user input of temp table
if formate of created date not YYYY-MM-DD then reject by update status field of temp table to be Notvalid
and if formate of created date is YYYY-MM-DD then update status by Valid
CREATE TABLE #TempPC
(
[ID] INT IDENTITY ,
CreatedDate varchar(12),
status varchar(200)
)
insert into #TempPC
(
CreatedDate
)
select '2022-05-09'
union
select '12-04-2022'
Expected result
CreatedDate Status
2022-05-09 Valid
12-04-2022 NotValid
[/INST]CREATE TABLE #TempPC
(
[ID] INT IDENTITY ,
CreatedDate varchar(12),
status varchar(200)
)
insert into #TempPC ( CreatedDate )
select '2022-05-09'
union all
select '12-15-2022'
union all
select '13-04-2022'
Select CreatedDate
,Case when try_Convert(date,CreatedDate,120) is null then 'NotValid' else 'Valid' end Status
from #TempPC</s> |
<s>[INST]how to remove 00:00:00.000 that exist on right of string ?
I work on sql server 2017 i have nvarchar(20) field have value as
2022-09-05 00:00:00.000
i need it to be
2022-09-05
so how to remove 0 on right of string
meaning how to remove
00:00:00.000
Expected result will be
2022-09-05
[/INST]CREATE TABLE #TempPC
(
[ID] INT IDENTITY ,
CreatedDate varchar(23) -- your string datetime length is 23
)
insert into #TempPC ( CreatedDate )
select '2022-09-05 00:00:00.000'
Select
Try_Convert(Date,CreatedDate),
Try_Cast(CreatedDate as date),
Left(CreatedDate,10),
Replace(CreatedDate,' 00:00:00.000','') ,
Substring(CreatedDate, 1,10) ,
Stuff(CreatedDate, 11,13,'')
from #TempPC</s> |
<s>[INST]How to replace existing value in table with new value in a query
I have a table which have columns Country, Region and Sales. Actually I have 70 columns in my table.Its just a sample data.
Now my requirement is I need to create a query which will select all columns from the table, but I have to replace country value as Unknown if it is null.
Could any one please help how to do[/INST]In SSMS right click on the table, use script as SELECT. Then scroll down to the Country column and change is to
ISNULL(Country, 'Unknown') as Country</s> |
<s>[INST]How to trap errors in SQL Scripts
We use scripts to add columns to our data tables like the one below. If the column already exists in the table, then the script crashes. Is there a way to trap this error so that script does not crash?
/* Add new column to dbo.cldoctype */
set xact_abort on
begin transaction
ALTER TABLE cldoctype ADD packet varchar(10) NULL
commit transaction
[/INST]Try the following:
begin transaction
if not exists (select 1 from INFORMATION_SCHEMA.Columns where table_schema = 'dbo' and table_name='clDocType' and column_name = 'packet') -- check for column's existence
ALTER TABLE cldoctype ADD packet varchar(10) NULL</s> |
<s>[INST]Out of range data conversion error
Dear Experts,
I am getting this error on one of the SQL jobs.
declare @month int=null
Set @month=12
select * from Table_A where CAST(CONVERT(datetime, TableLocalDate, 131) AS DATE) <=DATEADD(MONTH,@Month*-1, GETDATE())
**"The conversion of a varchar data type to a date time data type resulted in an out-of-range value"**
The TableLocalDate is of varchar data type
Could you please advise how this query can be fixed? [/INST]The reason you are getting this that one or more rows have data that is not a valid type 131 date. How you fix it depends on what you want done. If you want to find all the rows with bad data so that you can fix them you can do
select * from @T where CAST(TRY_CONVERT(datetime, TableLocalDate, 131) AS DATE) Is NULL And TableLocalDate Is Not NULL
That will show you the rows with bad data. You can then correct the data.
If, instead, you want to have SQL ignore any rows with bad TableLocalDate values, you can do
select * from @T where CAST(TRY_CONVERT(datetime, TableLocalDate, 131) AS DATE) <=DATEADD(MONTH,@Month-1, GETDATE())
If you do that you won't get any errors and none of the rows which would have caused the error will be in your result.</s> |
<s>[INST]Updates are taking a long time... need help diagnosing the cause
I am using NI Teststand; this tool provides a schema to implement on a relational DB, and I have implemented it on SQL Server.
Every so often the DB inserts are taking a long time to complete.
Unfortunately, this tool calls a DLL to perform the updates. So I can't directly see what queries are running.
1\) Is there a transaction log where I can see the queries?
2) Is there a log where I can see the time each query took to run?
3) Is there a tool that would help me identify what was slow? (I suspect FK lookups)
I am not a DB guru, but if I can prove this solution is viable, I might be able to hire one. ;)
[/INST]There are a couple of options. If you are on SQL 2016 or later, enable Query Store:
ALTER DATABASE YourDB SET QUERY_STORE = ON
Query store will store information about query execution aggregated by hour and execution plan. In Management Studio, you can find reports that helps you to dig around in this data.
You can also use Trace and Extended Events to track execution. Easiest to use is Profiler which you can start and point to your server to see what is being executed on the server. Beware though, that using Profiler on production system can have severe effects on performance, particularly if you have many quick queries. You should only run it for a limited amount of time. But it can be a good tool to find out what query is being executed if you press that button. At least as long as you can set up good filters. Or have the server to your own.</s> |
<s>[INST]We are geting a performance issue after applying SQL 2016 SP3. Has anyone else had this ?
We have two instances of sql to which we have applied SQL 2016 SP3, plus the latest hotfix.
The result of SELECT @@VERSION is
"Microsoft SQL Server 2016 (SP3-OD) (KB5006943) - 13.0.6404.1 (X64) Oct 18 2021 09:37:01 Copyright (c) Microsoft Corporation Enterprise Edition: Core-based Licensing (64-bit) on Windows Server 2016 Standard 10.0 <X64> (Build 14393: ) (Hypervisor) "
both instances are the target ( OLEDB data destinations) of SSIS packages running from seperate servers running sql server 2019.
Since applying Sql 2016 SP3 plus the hotfix we are seeing the average execution of the ssis packages that talk to these sql boxes roughly double.
The performance issues align with when sql 2016 SP3, plus hotfix was applied. No updates have been applied to the sql 2019 servers.
We are not aware of any later SP's or hotfixes for sql 2016.
Can anyone help us ?
[/INST]SP3 may or may not have something to do with it. That is, it could be a plain parameter-sniffing issue. Since you had to restart SQL Server, the cache was cleared, and all queries had to be recompiled.
Do you have Query Store enabled for the databases? And did you have so before you installed SP3?</s> |
<s>[INST]IIF statement query using SQL server
hey,
can anyone point me in the right direction?
Using the following statement I can calculate conversions taking place within the same month:
IIF(datepart(wk,appl_createddate) <= datepart(wk,appl_conversiondate), 1, 0)
however, if I want to return values where appl_conversiondate =< 4 weeks after appl_createddate how would I go about achieving this?
Ultimately I'm trying to capture conversions that take place between months as well so the conversion rate isn't skewed, hope this makes sense![/INST]You can use DATEDIFF function and test if the number of weeks is greater than 4 or less, e.g.
SELECT DATEDIFF(WEEK, CURRENT_TIMESTAMP, DATEADD(MONTH, 1, CURRENT_TIMESTAMP)) AS WeeksDifference</s> |
<s>[INST]how much truth is there to this theory about avoiding dirty reads in production mission critical reporting?
Hi we run 2019 enterprise. Its been years since i read details on how dirty reads happen. And even then my eyes glossed over. But i've witnessed the problem firsthand so i try to talk customers out of it whenever possible. You know how the conversation goes in certain cultures "it has probably occurred in that app, it would be expensive to prove but why not stop a bad habit and remove the mystery".
One of my peers who knows a lot and agrees shared this opinion when i spoke up recently...
***Most NO LOCK issues are avoided with keys on the database table and having the engine not treat the table as a heap, I doubt the numbers would be affected with our table structures, but still running off of the OLTP system can have numbers that could be partially done and a bad practice.***
I have to admit that I would have thought keys don't help to avoid the problem especially in a very normalized multi join architecture with all kinds of indexes. And i would have to read a little to see what if anything the heap has to do with this. Is he making a good point?
[/INST]I would say that is quite a big of hogwash.
Say that you have a query like this:
SELECT SUM(amount) FROM tbl -- WITH (NOLOCK)
WHERE account = @account
To keep things simple, let's assume that the optimizer considers any index on account useless, because the query hits too many rows. This, there will be a table scan.
There are two ways a table with a clustered index can be scanned: 1) Following the doubly-linked list between the pages 2) Scanning the Index Allocation Map.
The latter is unsafer, as rows may be missed if there are page splits going on. Therefore, the Storage Engine will only use IAM scans under one of two conditions: 1) There cannot be any simultaneous changes. (TABLOCK or database/filegroup readonly). 2) You explicitly say you don't care. That is NOLOCK.
Also note that keys or not are not that really relevant. What has some relevance is if there is a clustered index. Which indeed there will be by default if you say PRIMARY KEY and don't explicitly say NONCLUSTERED. But it does not have to be like that.</s> |
<s>[INST]Sql Server Where Clause If else
Below is a brief outline of one of my queries. Here I am showing stocks without 0. If Purchases_Qty are> 0, Sales_Qty are> 0 and Stocks are = 0 then I can't see that row. It becomes hidden.
My requirement is - if the purchases_Qty are> 0 or sales_Qty> 0, then the stock = 0 will show it. And if Purchases_Qty = 0 and Sales_Qty = 0, then the stock will be <> 0
Thanks in advance to the experienced collaborators.
with Cte as( select
a.Date,
a.Company_Name,
a.Product_Code,
a.Product_Name,
isnull(a.purchase,0) as purchase_Qty,
isnull(b.Sale,0) as Sale_Qty,
stock=isnull(a.purchase,0)-isnull(b.Sale,0)
from
(select Date, Company_Name,Product_Code,Product_Name,sum(isnull(Qty,0)) as purchase from tbl_purchase
group by Date, Company_Name,Product_Code,Product_Name) a
left join
(select Date, Company_Name,Product_code,Product_Name,SUM(isnull(Qty,0)) as Sale from tbl_sales
group by Date, Company_Name,Product_code,Product_Name) b
on a.Company_Name=b.Company_Name
and a.Product_Code=b.Product_code
and a.Product_Name=b.Product_Name
and a.Date=b.Date
)
select Date,Company_Name,Product_Code,Product_Name,purchase_Qty,Sale_Qty,stock from cte
where Date between '2022-04-21' and '2022-04-21'
**and stock<>0**
[/INST]Sound like you should change
and stock <> 0
to
and (purchaes_Qty > 0 or Sales_Qty > 0 or stock <> 0</s> |
<s>[INST]cannot recall the term used for a very detailed, highly disciplined data warehousing approach that includes processes
Hi, this is embarrassing but there is a discipline out there that in addition to data, captures something about processes and perhaps workflows in the warehouse as well.
I looked at it years ago, thought it had some merit, would be expensive and in some installations might possibly be overkill.
Does anybody remember what it is called? I want to do a re read.[/INST]There are many. Without knowing more details it is hard to guess.
"Data Vault" is one I have used in the past. I would not really recommend it for most implementations.</s> |
<s>[INST]Need SQL Query to count values over multiple columns
Hello!
I am trying to get my information in Wide format instead of Long and I can't figure out what I'm doing wrong.
I started with:
SELECT
codetable.status_code,
codetable.client_code,
COUNT(*)
FROM
debt
GROUP BY codetable.client_code, codetable.status_code
Which is what gave me the long format. 3 columns - Customer Client Code, Debt Status Code, and Count
I keep receiving an error message from the system I'm using regarding the following lines of code. There were several different iterations of error message so I won't post them. I have had some success, i.e. getting wide format, but I could not get a count of each code under each 'codetable.status_code' (example, ACT, PIF, SIF, etc).
SELECT
codetable.client_code,
MAX(CASE WHEN status_code = 'WRITTEN' then status_code end) as WRITTEN,
MAX(CASE WHEN status_code = 'SONN' then status_code end) as SONN,
MAX(CASE WHEN status_code = 'SIP' then status_code end) as SIP,
MAX(CASE WHEN status_code = '1099C_SENT' then status_code end) as "1099C_SENT",
MAX(CASE WHEN status_code = 'ACT' then status_code end) as ACT,
MAX(CASE WHEN status_code = 'ALLE' then status_code end) as ALLE,
MAX(CASE WHEN status_code = 'ATTY' then status_code end) as ATTY,
MAX(CASE WHEN status_code = 'BNK' then status_code end) as BNK,
MAX(CASE WHEN status_code = 'BPR' then status_code end) as BPR,
MAX(CASE WHEN status_code = 'CAN' then status_code end) as CAN,
MAX(CASE WHEN status_code = 'DEC' then status_code end) as DEC,
MAX(CASE WHEN status_code = 'DST' then status_code end) as DST,
MAX(CASE WHEN status_code = 'DXB' then status_code end) as DXB,
MAX(CASE WHEN status_code = 'NEW' then status_code end) as NEW,
MAX(CASE WHEN status_code = 'PAY' then status_code end) as PAY,
MAX(CASE WHEN status_code = 'PIP' then status_code end) as PIP,
MAX(CASE WHEN status_code = 'PTP' then status_code end) as PTP,
MAX(CASE WHEN status_code = 'PTS' then status_code end) as PTS,
MAX(CASE WHEN status_code = 'RESOLVED' then status_code end) as RESOLVED,
MAX(CASE WHEN status_code = 'SL' then status_code end) as SL,
COUNT(*)
FROM
debt
GROUP BY codetable.client_code
At this point I don't care how long the code needs to be. I need 21 columns, including Customer Client Code and the individual client codes above and no Count column.
What I have now is 22 columns, including a Count column. I have read several articles presented on this site based on my question and I just feel like since none of them helped me specifically that I must be missing something else.
If this is enough information?
If so, how do I get the results I'm looking for?? :([/INST]Try replacing all of *MAX* with *COUNT*. Remove _COUNT(*)_.</s> |
<s>[INST]"Page inconsistency detected" ERROR
I'm getting a "Page inconsistency detected" error. What kind of path should I follow? how should I go about solving this problem[/INST]You should run DBCC CHECKDB to get an idea of how damaged the database is.
Most likely it will tell you that the lowest level for repair is REPAIR_WITH_ALLOW_DATA_LOSS.
The action to take is find a clean backup to restore the database. If DBCC reports that only this page (or maybe a few more), it is in fact possible to restore only this page(s). If you take this path, you also need to apply transaction log backups before the database becomes usable.
One thing to keep in mind is that pages do not get corrupted out of the blue. Corruption is almost always due to faulting hardware or issues in the I/O subsystem. Therefore there is all reason to track down the root problem. Else the corruption will come back.</s> |
<s>[INST]Unable to DROP Table - permissions issue?
Hi,
I am using Microsoft SQL Server Standard (64-bit) version 11.0.7507.2. The computer running SQL Server is on a Domain. I am logged on to the SQL Server computer through a Remote Desktop connection. I believe the account I have logged on with is an Administrator account on the Domain. I am able to log on to SQL Server Management Studio using Windows Authentication.
I wanted to DROP a database using the following command:
DROP DATABASE PKYICNJ
... When I try to execute the above command, I get a message saying 'Cannot drop the database 'PKYICNJ', because it does not exist or you do not have permission.'
In the left pane of SSMS (Object Explorer), when I look in the 'Security' branch in the first level of the hierarchy below my server name, I see only the following three logins...
BUILTIN\Users
LUMINER\Domain Users
sa
... When I look under 'Server Roles', I see several server roles listed, but the only role that has a member is the 'sysadmin' role. The only member of the 'sysadmin' role is the 'sa' login.
I do not currently know the password for the 'sa' account, as this server was setup by someone other than myself who is know longer working with my company.
I have two questions:
(1) Based on what I have said, is my inability to DROP a database likely due to inadequate permissions? (I am certain that the database I am trying to drop exists)
(2) If my problem is related to inadequate permissions, is there any way I can hope to get around this if I am unable to find the 'sa' password?
I have our network / domain Administrator at my service, so if it is possible to elevate my permissions in SQL Server through Windows Authentication (without the 'sa' password), he should be able to do it. Unfortunately, he does not know the 'sa' password either.
Any suggestions will be greatly appreciated.
Thanks in advance,
Paul
[/INST]At least the way this server is configured now, I can see that 'sa' is the only member assigned to the 'sysadmin' role.
Nah, because you are not member of sysadmin, you cannot see the other members. (There are a few builtin for services.)
> Your mention that if the account I'm using is not a member of the 'sysadmin' role, I might not be able to stop SQL Server
No, this is a Windows action, and you need the appropriate Windows permission to stop and start services. I don't think you have to be Administrator, so theoretically you could have permission to start/stop services without being Administrator, but I would not hold that as likely.
In any case, it is not an acceptable situation to have a production server that no one in the organization can access. There is all reason to demand the IT firm to provide you documentation about which users/groups that have sysadmin access.</s> |
<s>[INST]Manual SQL Replication
Hello
Please help me with bellow case.
In my company we have 2 servers (production - name it "A" and data warehouse - name it "B"). On production server we have ERP data. On data warehouse we want to have copy of some tables from ERP tables. We wanted to use sql transactional replication. But when we configured replication on ERP data database we cannot upgrade ERP system.
For now we created sql procedures on server "B" which update tables on "B" based on "A". This procedures are run automaticaly by jobs.
Any better solutions?
[/INST]There might be better solutions, but then again, if what you have is working for you, that should be good enough, I think.
As for suggesting other options, we would need to know more about the gory details. There are plenty of ways to skin this cat, but the exact nature of the cat can mean that some ways works better or worse than others.
As for setting up transactional replication with a third-party system, this is something you need to discuss with the vendor. And if they say no, you should take that as an answer.</s> |
<s>[INST]sql databse relationships architecture?
Hi im arslan ,
i have seen first time ever sql database tables working without foreign key relation in big project .
what is the best practise to use relational database ,1 with foreign keys . 2 without foreign keys?[/INST]Foreign key.
Foreign key constraints are as essential to a relational database as are tables and columns
The obvious problem with the lack of foreign keys is that a database can not enforce referential integrity, and tables relations are not clear</s> |
<s>[INST]Joins dynamicall based on the column list available
Dear All,
Could you please suggest a way to achieve a way to join two tables where join columns are dynamic in nature as below.
Table A: has two columns
Column_toLook, Column_value
India,100
India,101
India,102
UK,200
UK,201
US,300,
US,301
Table 2 : has around 6 countries of data (static columns here)
India,UK,US,Japan,Aus,germany
100,200,300,400,500,600
101,201,301,401,501,601
105,205,305,405,505,605
Join condition :
First we need to take the list of countries present in Table A --> Column_toLook data and based on the column name come to table B, match the column_values in this tableB based on matching country name, Look for the Column_value presence in TableB, if matches add 'TRUE' if not 'FALSE' as a flag column.
if we get more countries in table A tomorrow, like japan which is not present in the current data, we have to consider this dynamically and match the Japan column values in TABLE B and add a value in FLAG column.
Over all, we need to have another column as FALG with TRUE or FALSE based on dynamic column names coming from Table A.
\--> I tried to convert the Table A Column_tolook data as Column names like Dynamic PIvot , but not able join it dynamically with table B. Because these data in COlumn A can vary daily.
Expected Output :
All the columns from Table B and an extra column as Flag with TRUE/FALSE in it.
Many thanks in advance.
[/INST]SELECT ...
FROM tbl1 a
JOIN tbl2 b ON a.ColumnValue = CASE a.ColumnToLookat
WHEN 'japan' THEN japan
WHEN 'india' THEN india
--etc
END
Yes, that is not particularly appetising. But as Ronen points out, this is what happens when you make a incorrect design decision.</s> |
<s>[INST]I restored a DB but it does not allow me to create a Database Diagram
I am using SQL Server Management Studio (version 18.12.1) and just restored a database not created by me, and when I try to create a DB diagram I get an error like this:
Cannot execute as thee database principal because the principal "dbo" does not exist, this type of principal cannot be impersonated, or you do not have permission, (Microsoft SqlServer Error: 15517)
The database is Microsoft SQL Server Express version 15.0.4153.1
If I create a database from scratch I can create db diagrams!!! But not with these other databases... what can I do to fix this?[/INST]This is due to that the SID for the dbo inside the database does not match the owner_sid in sys.databases.
A simple way out is to change the database owner:
ALTER AUTHORIZATION ON DATABASE::YourDB TO YourDomain\YourUser</s> |
<s>[INST]how to make union all in case of some table not exist ?
I work on sql server 2019 i have three tables a and b and c
select id,name from tableA
union
select id,name from tableB
union
select id,name from table C
union
select id,name from TableC
suppose table C not exist
so how to avoid error and execute union without any error [/INST]Solution 1: Dynamically modify the UNION statement based on whether the table exists.
Check these two alternative methods:
CREATE TABLE tableA(id INT,name VARCHAR(20))
CREATE TABLE tableB(id INT,name VARCHAR(20))
CREATE TABLE tableC(id INT,name VARCHAR(20))
DROP TABLE tableA;
DROP TABLE tableB;
DROP TABLE tableC
--Method 1
DECLARE @sql NVARCHAR(MAX)
SELECT @sql = CASE WHEN name = 'tableA' THEN 'select id,name from tableA ' END
FROM sys.tables WHERE name = 'tableA'
SELECT @sql += CASE WHEN @sql IS NOT NULL AND name = 'tableB' THEN ' union all select id,name from tableB'
WHEN @sql IS NULL AND name = 'tableB' THEN 'select * from tableB' END
FROM sys.tables WHERE name = 'tableB'
SELECT @sql += CASE WHEN @sql IS NOT NULL AND name = 'tableC' THEN ' union all select id,name from tableC'
WHEN @sql IS NULL AND name = 'tableC' THEN 'select * from tableC' END
FROM sys.tables WHERE name = 'tableC'
PRINT @sql
EXEC sp_executesql @sql
GO
--Method 2
DECLARE @tableNames VARCHAR(MAX)
DECLARE @sql VARCHAR(MAX)
DECLARE @tablelist TABLE(tablename VARCHAR(50))
SET @tableNames='tableA,tableB,tableC'
SET @sql = 'select name from sys.objects where name in (''' + REPLACE(@tableNames, ',',''',''') + ''')';
INSERT INTO @tablelist EXEC (@sql);
--creating query with union all
SELECT @sql = @sql + 'Select id,name from ' + tablename + ' Union All ' From @tablelist;
SET @sql = LEFT(@sql, len(@sql) - 9);
PRINT @sql
EXEC sp_executesql @sql;
Solution 2: Use a table variable, insert only the rows of the tables that exist in your database. Then select the records of the table variable, and you will have the rows of each existing table.
DECLARE @recordsExistingTables TABLE(id INT,name VARCHAR(20));
IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'TableA'))
BEGIN
INSERT INTO @recordsExistingTables SELECT id,name FROM TableA
END
IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'TableB'))
BEGIN
INSERT INTO @recordsExistingTables SELECT id,name FROM TableB
END
IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'TableC'))
BEGIN
INSERT INTO @recordsExistingTables SELECT id,name FROM TableC
END
SELECT * FROM @recordsExistingTables;</s> |
<s>[INST]how to remove 18 milion bookid from table without using delete ?are there are any idea to more faster
i work on sql server 2019 i have two tables table books and booksdetails
i need to delete all data from table books details that have book id related on table books
so i make it as below
books table have 20milions book id
bookdetails have 19milion book id related
after delete bookdetails will have one milion
delete d from dbo.bookpublishdetails d
inner join dbo.books b on b.bookid=d.bookid
so result of applying delete will delete 18 milion from table bookdetails
so it will take too much time reach too 1 hour although i have clustered indexes on bookid on table dbo.books
and nonclusterd index on table dbo.bookpublishdetails on colunmn book id
after delete i will use table dbo.bookpublishdetails to more processes as select and delete and insert on table
bookdetails
**so are there are another logic best from delete to avoid too much time consumed on delete ?**
ddl details
create table dbo.book
(
bookid int,
bookname varchar(200),
ISBN varchar(20),
PageNumbers int,
PublishedBy varchar(200)
)
create clustered index book_ix on dbo.book(bookid)
create table dbo.bookpublishdetails
(
bookdetailsid int,
bookid int,
BookPublishedId int,
PublishedBy varchar(300)
)
create nonclustered index bookdetails_ix on dbo.bookpublishdetails(bookid)
[/INST]Agreed with CosmogHong\-MSFT
I think another options to do this is,
Insert joins result into temp table
Select d.bookid INTO #tempDel from dbo.bookpublishdetails d
inner join dbo.books b on b.bookid=d.bookid
DELETE d dbo.bookpublishdetails d
inner join #tempDel b on b.bookid=d.bookid
If this also takes time then you may try below,
Select bookid INTO #tempbooks from dbo.books
Select d.bookid INTO #tempDel from dbo.bookpublishdetails d
inner join #tempbooks b on b.bookid=d.bookid
DELETE d dbo.bookpublishdetails d
inner join #tempDel b on b.bookid=d.bookid
Hope this will be fine..</s> |
<s>[INST]Complex calculation in sql server 2019
Hello,
I am using sql server 2019.
i am trying to have a sql script which shows
customer_price-vehicle_cost
If customer_price-vehicle_cost in Positive than Profit
If customer_price-vehicle_cost in Negative than Loss
Else No Gain
The 2nd Part of script shows loss happen only when difference between (requested_arrival-actual_arrival)>1 hour the result has to shown in column
called as Reason contain hour value
So There will be 2 result set.
The Date column was kept in varchar as suitable datatype is not available in sql server 2019
sample data:
DECLARE @LOCAL_TABLEVARIABLE TABLE
(
TRACKID VARCHAR (50),
ChannelSource VARCHAR (50),
created_date VARCHAR (50),
delivered_date VARCHAR (50),
actual_arrival VARCHAR (50),
requested_arrival VARCHAR (50),
customer_price FLOAT,
vehicle_cost FLOAT
)
INSERT @LOCAL_TABLEVARIABLE
SELECT 'Z1G510A','sales', '2021-12-09 09:16:09+00','2021-12-15T02:40:39+01:00','2021-12-15 1:27:56','2021-12-15 0:45:00',286.4,320 UNION ALL
SELECT 'B18EAE2','website', '2022-01-21 13:26:04+00','2022-01-26T12:47:39+01:00','2022-01-26 10:00:00','2022-01-26 10:00:00',1021,1000 UNION ALL
SELECT 'E116A40','website','2022-01-07 13:33:21+00','2022-01-17T10:09:01+01:00','2022-01-14 7:00:00','2022-01-14 7:00:00',585,650 UNION ALL
SELECT '91H8B6C','website','2022-02-09 11:47:09+00','2022-02-11T09:30:48+01:00','2022-02-11 8:03:21','2022-02-11 17:00:00',201,204 UNION ALL
SELECT 'S1Z165F','sales', '2021-12-02 08:14:42+00','2021-12-10T10:28:19+01:00','2021-12-10 8:00:00','2021-12-10 13:00:00',500.8,650 UNION ALL
SELECT 'F1D1308','website', '2021-12-16 11:05:12+00','2021-12-23T13:55:31+01:00','2021-12-23 8:54:14','2021-12-22 16:00:00',0.8,1 UNION ALL
SELECT '21577CA','website', '2021-12-08 12:05:18+00','2021-12-22T15:01:05+01:00','2021-12-22 8:50:00','2021-12-23 16:00:00',960,1200 UNION ALL
SELECT 'X1FF3A9','website','2022-01-27 13:44:48+00','2022-01-31T12:30:40+01:00','2022-01-31 12:09:20','2022-01-31 14:00:00',495,330 UNION ALL
SELECT 'S1V7021','website','2022-02-18 13:04:56+00','2022-02-22T12:18:28+01:00','2022-02-22 10:52:39','2022-02-23 16:04:00',730,680 UNION ALL
SELECT 'P1J9B33','website','2021-11-24 09:55:07+00','2021-12-07T10:33:04+01:00','2021-12-06 16:00:02','2021-12-06 16:00:00',0.8,1 UNION ALL
SELECT 'U1Q436B','referral','2022-01-21 09:30:22+00','2022-01-24T16:01:33+01:00','2022-01-24 13:00:27','2022-01-24 12:00:00',2145,1626 UNION ALL
SELECT 'U1R9C50', 'website', '2022-01-17 09:33:53+00','2022-02-04T14:41:36+01:00','2022-02-04 11:33:29','2022-02-04 15:00:00',3300,2200 UNION ALL
SELECT '61C4EC4','sales', '2021-12-02 09:11:49+00','2021-12-10T02:01:06+01:00','2021-12-09 21:30:20','2021-12-10 0:15:00',254.4,310 UNION ALL
SELECT 'N1W909D','website','2022-02-02 09:50:21+00','2022-02-21T15:03:51+01:00','2022-02-15 8:33:21','2022-02-16 16:00:00',1290,860 UNION ALL
SELECT 'B1X5B6C','website','2021-12-09 09:46:06+00','2021-12-17T08:31:18+01:00','2021-12-17 7:14:12','2021-12-17 15:00:00',1096,1370 UNION ALL
SELECT '61RC3D6','website','2021-12-13 14:49:32+00','2021-12-22T12:07:31+01:00','2021-12-16 7:00:48','2021-12-16 21:00:00',445.6,557 UNION ALL
SELECT '91T1FDF','website','2022-02-08 08:40:12+00','2022-02-09T13:59:45+01:00','2022-02-09 13:57:13','2022-02-09 15:00:00',420,280 UNION ALL
SELECT 'N1H4578','website','2021-12-07 09:28:58+00','2022-01-03T14:41:53+01:00','2021-12-28 12:00:20','2021-12-28 16:00:00',384,480 UNION ALL
SELECT 'P156CE5','website','2022-02-16 08:38:44+00','2022-02-18T12:59:19+01:00','2022-02-18 7:30:05','2022-02-18 21:00:00',500,500 UNION ALL
SELECT '61U06CE','website','2021-12-31 09:46:21+00','2022-01-04T14:10:22+01:00','2022-01-04 11:24:53','2022-01-04 16:00:00',336,195 UNION ALL
SELECT 'Y1PA1FC','website','2021-12-01 11:54:30+00','2021-12-03T14:01:59+01:00','2021-12-03 7:01:47','2021-12-03 16:00:00',760,950 UNION ALL
SELECT '316381B','sales','2022-01-25 12:00:20+00','2022-02-01T15:41:49+01:00','2022-02-01 15:00:27','2022-02-01 14:45:00',672,300 UNION ALL
SELECT 'H1V067F','website','2022-01-19 12:22:11+00','2022-02-04T13:05:24+01:00','2022-02-03 13:11:06','2022-02-03 16:00:00',1117.5,745 UNION ALL
SELECT 'X1LC768','website','2021-12-06 14:17:16+00','2021-12-09T12:57:54+01:00','2021-12-09 11:30:53','2021-12-08 18:00:00',480,670 UNION ALL
SELECT '81P3D0D','website','2022-02-15 10:18:47+00','2022-02-17T08:43:16+01:00','2022-02-16 14:00:04','2022-02-16 15:00:00',3448.5,2299 UNION ALL
SELECT '71J3EEA','website','2022-01-03 09:04:10+00','2022-01-05T11:30:29+01:00','2022-01-05 7:45:22','2022-01-05 8:00:00',336,195 UNION ALL
SELECT 'K1QAB19','website','2022-02-04 14:58:06+00','2022-02-09T08:17:34+01:00','2022-02-08 15:32:29','2022-02-08 18:00:00',584,600 UNION ALL
SELECT 'Y1YE019','website','2022-01-19 13:28:51+00','2022-01-22T07:35:27+01:00','2022-01-22 5:40:00','2022-01-22 6:00:00',730,800 UNION ALL
SELECT 'A1M9DE2','website','2022-01-17 12:14:12+00','2022-01-28T13:11:58+01:00','2022-01-28 12:43:37','2022-01-27 16:00:00',5535,5535
[/INST]You did not give us the expected result, so I was not able to verify this result:
SELECT TRACKID, Profit = CASE WHEN customer_price > vehicle_cost THEN customer_price - vehicle_cost END,
Loss = CASE WHEN customer_price < vehicle_cost THEN customer_price - vehicle_cost END,
Hours = CASE WHEN datediff(MINUTE, actual_arrival, requested_arrival) > 60
THEN datediff(MINUTE, actual_arrival, requested_arrival) / 60
END
FROM @LOCAL_TABLEVARIABLE
> The Date column was kept in varchar as suitable datatype is not available in sql server 2019
For the actual_arrival and requested_arrival the type `datetime2(0)` would work very well. For the other columns, I think `datetimeoffset(0)` is a good pick. Storing date/time in string column will always end in tears.</s> |
<s>[INST]complex calculation in sql server 2019
I am trying to write sql code to find out which channelsource generate maximum profit
and based on the calculation `(customer_price-vehicle_cost)`, Ranking for profit in the alias column Remarks
contain value like Top Highest profit , or 2nd highest or 3rd highest.
sample data
DECLARE @LOCAL_TABLEVARIABLE TABLE
(
TRACKID VARCHAR (50),
ChannelSource VARCHAR (50),
created_date VARCHAR (50),
delivered_date VARCHAR (50),
actual_arrival VARCHAR (50),
requested_arrival VARCHAR (50),
customer_price FLOAT,
vehicle_cost FLOAT
)
INSERT @LOCAL_TABLEVARIABLE
SELECT 'Z1G510A','sales', '2021-12-09 09:16:09+00','2021-12-15T02:40:39+01:00','2021-12-15 1:27:56','2021-12-15 0:45:00',286.4,320 UNION ALL
SELECT 'B18EAE2','website', '2022-01-21 13:26:04+00','2022-01-26T12:47:39+01:00','2022-01-26 10:00:00','2022-01-26 10:00:00',1021,1000 UNION ALL
SELECT 'E116A40','website','2022-01-07 13:33:21+00','2022-01-17T10:09:01+01:00','2022-01-14 7:00:00','2022-01-14 7:00:00',585,650 UNION ALL
SELECT '91H8B6C','website','2022-02-09 11:47:09+00','2022-02-11T09:30:48+01:00','2022-02-11 8:03:21','2022-02-11 17:00:00',201,204 UNION ALL
SELECT 'S1Z165F','sales', '2021-12-02 08:14:42+00','2021-12-10T10:28:19+01:00','2021-12-10 8:00:00','2021-12-10 13:00:00',500.8,650 UNION ALL
SELECT 'F1D1308','website', '2021-12-16 11:05:12+00','2021-12-23T13:55:31+01:00','2021-12-23 8:54:14','2021-12-22 16:00:00',0.8,1 UNION ALL
SELECT '21577CA','website', '2021-12-08 12:05:18+00','2021-12-22T15:01:05+01:00','2021-12-22 8:50:00','2021-12-23 16:00:00',960,1200 UNION ALL
SELECT 'X1FF3A9','website','2022-01-27 13:44:48+00','2022-01-31T12:30:40+01:00','2022-01-31 12:09:20','2022-01-31 14:00:00',495,330 UNION ALL
SELECT 'S1V7021','website','2022-02-18 13:04:56+00','2022-02-22T12:18:28+01:00','2022-02-22 10:52:39','2022-02-23 16:04:00',730,680 UNION ALL
SELECT 'P1J9B33','website','2021-11-24 09:55:07+00','2021-12-07T10:33:04+01:00','2021-12-06 16:00:02','2021-12-06 16:00:00',0.8,1 UNION ALL
SELECT 'U1Q436B','referral','2022-01-21 09:30:22+00','2022-01-24T16:01:33+01:00','2022-01-24 13:00:27','2022-01-24 12:00:00',2145,1626 UNION ALL
SELECT 'U1R9C50', 'website', '2022-01-17 09:33:53+00','2022-02-04T14:41:36+01:00','2022-02-04 11:33:29','2022-02-04 15:00:00',3300,2200 UNION ALL
SELECT '61C4EC4','sales', '2021-12-02 09:11:49+00','2021-12-10T02:01:06+01:00','2021-12-09 21:30:20','2021-12-10 0:15:00',254.4,310 UNION ALL
SELECT 'N1W909D','website','2022-02-02 09:50:21+00','2022-02-21T15:03:51+01:00','2022-02-15 8:33:21','2022-02-16 16:00:00',1290,860 UNION ALL
SELECT 'B1X5B6C','website','2021-12-09 09:46:06+00','2021-12-17T08:31:18+01:00','2021-12-17 7:14:12','2021-12-17 15:00:00',1096,1370 UNION ALL
SELECT '61RC3D6','website','2021-12-13 14:49:32+00','2021-12-22T12:07:31+01:00','2021-12-16 7:00:48','2021-12-16 21:00:00',445.6,557 UNION ALL
SELECT '91T1FDF','website','2022-02-08 08:40:12+00','2022-02-09T13:59:45+01:00','2022-02-09 13:57:13','2022-02-09 15:00:00',420,280 UNION ALL
SELECT 'N1H4578','website','2021-12-07 09:28:58+00','2022-01-03T14:41:53+01:00','2021-12-28 12:00:20','2021-12-28 16:00:00',384,480 UNION ALL
SELECT 'P156CE5','website','2022-02-16 08:38:44+00','2022-02-18T12:59:19+01:00','2022-02-18 7:30:05','2022-02-18 21:00:00',500,500 UNION ALL
SELECT '61U06CE','website','2021-12-31 09:46:21+00','2022-01-04T14:10:22+01:00','2022-01-04 11:24:53','2022-01-04 16:00:00',336,195 UNION ALL
SELECT 'Y1PA1FC','website','2021-12-01 11:54:30+00','2021-12-03T14:01:59+01:00','2021-12-03 7:01:47','2021-12-03 16:00:00',760,950 UNION ALL
SELECT '316381B','sales','2022-01-25 12:00:20+00','2022-02-01T15:41:49+01:00','2022-02-01 15:00:27','2022-02-01 14:45:00',672,300 UNION ALL
SELECT 'H1V067F','website','2022-01-19 12:22:11+00','2022-02-04T13:05:24+01:00','2022-02-03 13:11:06','2022-02-03 16:00:00',1117.5,745 UNION ALL
SELECT 'X1LC768','website','2021-12-06 14:17:16+00','2021-12-09T12:57:54+01:00','2021-12-09 11:30:53','2021-12-08 18:00:00',480,670 UNION ALL
SELECT '81P3D0D','website','2022-02-15 10:18:47+00','2022-02-17T08:43:16+01:00','2022-02-16 14:00:04','2022-02-16 15:00:00',3448.5,2299 UNION ALL
SELECT '71J3EEA','website','2022-01-03 09:04:10+00','2022-01-05T11:30:29+01:00','2022-01-05 7:45:22','2022-01-05 8:00:00',336,195 UNION ALL
SELECT 'K1QAB19','website','2022-02-04 14:58:06+00','2022-02-09T08:17:34+01:00','2022-02-08 15:32:29','2022-02-08 18:00:00',584,600 UNION ALL
SELECT 'Y1YE019','website','2022-01-19 13:28:51+00','2022-01-22T07:35:27+01:00','2022-01-22 5:40:00','2022-01-22 6:00:00',730,800 UNION ALL
SELECT 'A1M9DE2','website','2022-01-17 12:14:12+00','2022-01-28T13:11:58+01:00','2022-01-28 12:43:37','2022-01-27 16:00:00',5535,5535
SELECT * FROM @LOCAL_TABLEVARIABLE
Please help me how to do that using sql
I am using SQL SERVER 2019
[/INST]Check a complex query:
;
with P as
(
select ChannelSource, sum(customer_price - vehicle_cost) as profit
from @LOCAL_TABLEVARIABLE
group by ChannelSource
),
R as
(
select ChannelSource, profit, rank() over (order by profit desc) r
from P
)
select ChannelSource, profit,
choose(r, 'Top Highest', '2nd highest', '3rd highest') as Remark
from R
where r <= 3</s> |
<s>[INST]Group by based on 2 column with sum clause in sql server 2019
I am trying to developed code which shows profitability performance in different geographical areas.
geo area is defined in A1_Country and A2_Country column.
trying to arrange profit in desending order based on the region present in A1_Country and A2_Country. So basically all unique country from A1_Country and A2_Country.
profit calculation formula : MFR_price - DISTRIBUTOR_cost
Data:
DECLARE @LOCAL_TABLEVARIABLE TABLE
(
TRACKID VARCHAR (50),
ChannelSource VARCHAR (50),
created_date VARCHAR (50),
delivered_date VARCHAR (50),
actual_arrival VARCHAR (50),
requested_arrival VARCHAR (50),
MFR_price FLOAT,
DISTRIBUTOR_cost FLOAT,
A1_Country VARCHAR (50),
A2_Country VARCHAR (50)
)
INSERT @LOCAL_TABLEVARIABLE
SELECT 'Z1G510A','sales', '2021-12-09 09:16:09+00','2021-12-15T02:40:39+01:00','2021-12-15 1:27:56','2021-12-15 0:45:00',286.4,320,'DE','DE' UNION ALL
SELECT 'B18EAE2','website', '2022-01-21 13:26:04+00','2022-01-26T12:47:39+01:00','2022-01-26 10:00:00','2022-01-26 10:00:00',1021,1000 ,'DE','DE' UNION ALL
SELECT 'E116A40','website','2022-01-07 13:33:21+00','2022-01-17T10:09:01+01:00','2022-01-14 7:00:00','2022-01-14 7:00:00',585,650,'DE','DE' UNION ALL
SELECT '91H8B6C','website','2022-02-09 11:47:09+00','2022-02-11T09:30:48+01:00','2022-02-11 8:03:21','2022-02-11 17:00:00',201,204,'DE','DE' UNION ALL
SELECT 'S1Z165F','sales', '2021-12-02 08:14:42+00','2021-12-10T10:28:19+01:00','2021-12-10 8:00:00','2021-12-10 13:00:00',500.8,650,'DE','DE' UNION ALL
SELECT 'F1D1308','website', '2021-12-16 11:05:12+00','2021-12-23T13:55:31+01:00','2021-12-23 8:54:14','2021-12-22 16:00:00',0.8,1 ,'DE','FR'UNION ALL
SELECT '21577CA','website', '2021-12-08 12:05:18+00','2021-12-22T15:01:05+01:00','2021-12-22 8:50:00','2021-12-23 16:00:00',960,1200,'DE','IT' UNION ALL
SELECT 'X1FF3A9','website','2022-01-27 13:44:48+00','2022-01-31T12:30:40+01:00','2022-01-31 12:09:20','2022-01-31 14:00:00',495,330,'DE','HU' UNION ALL
SELECT 'S1V7021','website','2022-02-18 13:04:56+00','2022-02-22T12:18:28+01:00','2022-02-22 10:52:39','2022-02-23 16:04:00',730,680,'DE','DE' UNION ALL
SELECT 'P1J9B33','website','2021-11-24 09:55:07+00','2021-12-07T10:33:04+01:00','2021-12-06 16:00:02','2021-12-06 16:00:00',0.8,1,'DE','CH' UNION ALL
SELECT 'U1Q436B','referral','2022-01-21 09:30:22+00','2022-01-24T16:01:33+01:00','2022-01-24 13:00:27','2022-01-24 12:00:00',2145,1626,'IT','DE' UNION ALL
SELECT 'U1R9C50', 'website', '2022-01-17 09:33:53+00','2022-02-04T14:41:36+01:00','2022-02-04 11:33:29','2022-02-04 15:00:00',3300,2200,'DE','ES' UNION ALL
SELECT '61C4EC4','sales', '2021-12-02 09:11:49+00','2021-12-10T02:01:06+01:00','2021-12-09 21:30:20','2021-12-10 0:15:00',254.4,310 ,'DE','DE' UNION ALL
SELECT 'N1W909D','website','2022-02-02 09:50:21+00','2022-02-21T15:03:51+01:00','2022-02-15 8:33:21','2022-02-16 16:00:00',1290,860 ,'RS','PL' UNION ALL
SELECT 'B1X5B6C','website','2021-12-09 09:46:06+00','2021-12-17T08:31:18+01:00','2021-12-17 7:14:12','2021-12-17 15:00:00',1096,1370 ,'RS','DE' UNION ALL
SELECT '61RC3D6','website','2021-12-13 14:49:32+00','2021-12-22T12:07:31+01:00','2021-12-16 7:00:48','2021-12-16 21:00:00',445.6,557 ,'DE','DE' UNION ALL
SELECT '91T1FDF','website','2022-02-08 08:40:12+00','2022-02-09T13:59:45+01:00','2022-02-09 13:57:13','2022-02-09 15:00:00',420,280 ,'HU','HU' UNION ALL
SELECT 'N1H4578','website','2021-12-07 09:28:58+00','2022-01-03T14:41:53+01:00','2021-12-28 12:00:20','2021-12-28 16:00:00',384,480 ,'DE','PL' UNION ALL
SELECT 'P156CE5','website','2022-02-16 08:38:44+00','2022-02-18T12:59:19+01:00','2022-02-18 7:30:05','2022-02-18 21:00:00',500,500 ,'DE','DE' UNION ALL
SELECT '61U06CE','website','2021-12-31 09:46:21+00','2022-01-04T14:10:22+01:00','2022-01-04 11:24:53','2022-01-04 16:00:00',336,195 ,'PL','PL' UNION ALL
SELECT 'Y1PA1FC','website','2021-12-01 11:54:30+00','2021-12-03T14:01:59+01:00','2021-12-03 7:01:47','2021-12-03 16:00:00',760,950 ,'DE','DE' UNION ALL
SELECT '316381B','sales','2022-01-25 12:00:20+00','2022-02-01T15:41:49+01:00','2022-02-01 15:00:27','2022-02-01 14:45:00',672,300 ,'PL','PL' UNION ALL
SELECT 'H1V067F','website','2022-01-19 12:22:11+00','2022-02-04T13:05:24+01:00','2022-02-03 13:11:06','2022-02-03 16:00:00',1117.5,745 ,'DE','DE' UNION ALL
SELECT 'X1LC768','website','2021-12-06 14:17:16+00','2021-12-09T12:57:54+01:00','2021-12-09 11:30:53','2021-12-08 18:00:00',480,670 ,'RS','RS' UNION ALL
SELECT '81P3D0D','website','2022-02-15 10:18:47+00','2022-02-17T08:43:16+01:00','2022-02-16 14:00:04','2022-02-16 15:00:00',3448.5,2299 ,'DE','DE' UNION ALL
SELECT '71J3EEA','website','2022-01-03 09:04:10+00','2022-01-05T11:30:29+01:00','2022-01-05 7:45:22','2022-01-05 8:00:00',336,195 ,'DE','DE' UNION ALL
SELECT 'K1QAB19','website','2022-02-04 14:58:06+00','2022-02-09T08:17:34+01:00','2022-02-08 15:32:29','2022-02-08 18:00:00',584,600 ,'DE','DE' UNION ALL
SELECT 'Y1YE019','website','2022-01-19 13:28:51+00','2022-01-22T07:35:27+01:00','2022-01-22 5:40:00','2022-01-22 6:00:00',730,800 ,'RS','PL' UNION ALL
SELECT 'A1M9DE2','website','2022-01-17 12:14:12+00','2022-01-28T13:11:58+01:00','2022-01-28 12:43:37','2022-01-27 16:00:00',5535,5535,'DE','DE'
SELECT * FROM @LOCAL_TABLEVARIABLE
Please help.
I am using sql server 2019
[/INST]So basically
SELECT A1_Country, A2_Country, SUM(Profit) AS RegionProfit
FROM tbl
GROUP BY A1_Country, A2_Country,
ORDER BY RegionProfit DESC
`Or am I misunderstanding something?</s> |
<s>[INST]Highest and Lowest sale for which month of year in sql
Hello,
Please help me on,
I am trying to get top 5 profit and top 5 loss based on channel source in a year.
profit = MFR_price - DISTRIBUTOR_cost
**Month**= Need to extract from created_date
Data:
DECLARE @LOCAL_TABLEVARIABLE TABLE
(
TRACKID VARCHAR (50),
distance INT,
ChannelSource VARCHAR (50),
created_date VARCHAR (50),
delivered_date VARCHAR (50),
MFR_price FLOAT,
DISTRIBUTOR_cost FLOAT
)
INSERT @LOCAL_TABLEVARIABLE
SELECT 'Z1G510A',91,'sales', '2021-12-09 09:16:09+00','2021-12-15T02:40:39+01:00',286.4,320 UNION ALL
SELECT 'B18EAE2',719,'website', '2022-01-21 13:26:04+00','2022-01-26T12:47:39+01:00',1021,1000 UNION ALL
SELECT 'E116A40',451,'website','2022-01-07 13:33:21+00','2022-01-17T10:09:01+01:00',585,650 UNION ALL
SELECT '91H8B6C',113,'website','2022-02-09 11:47:09+00','2022-02-11T09:30:48+01:00',201,204 UNION ALL
SELECT 'S1Z165F',315,'sales', '2021-12-02 08:14:42+00','2021-12-10T10:28:19+01:00',500.8,650 UNION ALL
SELECT 'F1D1308',983,'website', '2021-12-16 11:05:12+00','2021-12-23T13:55:31+01:00',0.8,1 UNION ALL
SELECT '21577CA',1052,'website', '2021-12-08 12:05:18+00','2021-12-22T15:01:05+01:00',960,1200 UNION ALL
SELECT 'X1FF3A9',904,'website','2022-01-27 13:44:48+00','2022-01-31T12:30:40+01:00',495,330 UNION ALL
SELECT 'S1V7021',621,'website','2022-02-18 13:04:56+00','2022-02-22T12:18:28+01:00',730,680 UNION ALL
SELECT 'P1J9B33',755,'website','2021-11-24 09:55:07+00','2021-12-07T10:33:04+01:00',0.8,1 UNION ALL
SELECT 'U1Q436B',1139,'referral','2022-01-21 09:30:22+00','2022-01-24T16:01:33+01:00',2145,1626 UNION ALL
SELECT 'U1R9C50',1953, 'website', '2022-01-17 09:33:53+00','2022-02-04T14:41:36+01:00',3300,2200 UNION ALL
SELECT '61C4EC4',14,'sales', '2021-12-02 09:11:49+00','2021-12-10T02:01:06+01:00',254.4,310 UNION ALL
SELECT 'N1W909D',1031,'website','2022-02-02 09:50:21+00','2022-02-21T15:03:51+01:00',1290,860 UNION ALL
SELECT 'B1X5B6C',1434,'website','2021-12-09 09:46:06+00','2021-12-17T08:31:18+01:00',1096,1370 UNION ALL
SELECT '61RC3D6',270,'website','2021-12-13 14:49:32+00','2021-12-22T12:07:31+01:00',445.6,557 UNION ALL
SELECT '91T1FDF',618,'website','2022-02-08 08:40:12+00','2022-02-09T13:59:45+01:00',420,280 UNION ALL
SELECT 'N1H4578',626,'website','2021-12-07 09:28:58+00','2022-01-03T14:41:53+01:00',384,480 UNION ALL
SELECT 'P156CE5',269,'website','2022-02-16 08:38:44+00','2022-02-18T12:59:19+01:00',500,500 UNION ALL
SELECT '61U06CE',230,'website','2021-12-31 09:46:21+00','2022-01-04T14:10:22+01:00',336,195 UNION ALL
SELECT 'Y1PA1FC',196,'website','2021-12-01 11:54:30+00','2021-12-03T14:01:59+01:00',760,950 UNION ALL
SELECT '316381B',132,'sales','2022-01-25 12:00:20+00','2022-02-01T15:41:49+01:00',672,300 UNION ALL
SELECT 'H1V067F',891,'website','2022-01-19 12:22:11+00','2022-02-04T13:05:24+01:00',1117.5,745 UNION ALL
SELECT 'X1LC768',538,'website','2021-12-06 14:17:16+00','2021-12-09T12:57:54+01:00',480,670 UNION ALL
SELECT '81P3D0D',788,'website','2022-02-15 10:18:47+00','2022-02-17T08:43:16+01:00',3448.5,2299 UNION ALL
SELECT '71J3EEA',487,'website','2022-01-03 09:04:10+00','2022-01-05T11:30:29+01:00',336,195 UNION ALL
SELECT 'K1QAB19',564,'website','2022-02-04 14:58:06+00','2022-02-09T08:17:34+01:00',584,600 UNION ALL
SELECT 'Y1YE019',3560,'website','2022-01-19 13:28:51+00','2022-01-22T07:35:27+01:00',730,800 UNION ALL
SELECT 'A1M9DE2',599,'website','2022-01-17 12:14:12+00','2022-01-28T13:11:58+01:00',5535,5535
Expected Output:
TRACKID, month(created_date), 1st Highest profit
TRACKID, month(created_date), 2nd Highest profit
TRACKID, month(created_date), 3rd Highest profit
TRACKID, month(created_date), 4th Highest profit
TRACKID, month(created_date), 5th Highest profit
TRACKID, month(created_date), Highest Loss
TRACKID, month(created_date), 2nd Highest Loss
TRACKID, month(created_date), 3rd Highest Loss
TRACKID, month(created_date), 4th Highest Loss
TRACKID, month(created_date), 5th Highest Loss
where month = any month of the year, what i am trying is top 5 profit of the year
and top 5 loss of the year
Thank you very much.
[/INST]Check a long query:
;
with D as
(
select *,
MFR_price - DISTRIBUTOR_cost as d
from @LOCAL_TABLEVARIABLE
),
P as
(
select *,
dense_rank() over (order by d desc) as r,
1 as o
from D
where d > 0
),
L as
(
select *,
dense_rank() over (order by d) as r,
2 as o
from D
where d < 0
),
U as
(
select *, choose(r, '1st', '2nd', '3rd', '4th', '5th') + ' Highest profit' as [Rank]
from P
where r <= 5
union all
select *, choose(r, '1st', '2nd', '3rd', '4th', '5th') + ' Highest loss'
from L
where r <= 5
)
select TRACKID, month(created_date) as [Month], [Rank]
from U
order by o, r</s> |
<s>[INST]Probability Distribution calculation in sql
Hello,
Is there any way to get probability in sql.
Suppose in remarks column we have more loss, and i am trying to show
if we decrease distance or change ChannelSource than there is probability
for particular TrackID to have gain instead of loss.
Pardon me if it is not possible in sql
Data:
DECLARE @MYTABLE TABLE
(
ID VARCHAR (50),
distance INT,
ChannelSource VARCHAR (50),
REMARKS VARCHAR (50)
)
INSERT @MYTABLE
SELECT 'Z1G510A',719,'ThirdParty','Loss' UNION ALL
SELECT 'B18EAE2',91,'website',' Gain' UNION ALL
SELECT 'E116A40',451,'ThirdParty','Loss' UNION ALL
SELECT '91H8B6C',113,'ThirdParty','Loss' UNION ALL
SELECT 'S1Z165F',315,'ThirdParty','Loss' UNION ALL
SELECT 'F1D1308',983,'website','Loss' UNION ALL
SELECT '21577CA',1052,'website','Loss' UNION ALL
SELECT 'X1FF3A9',904,'website','Gain' UNION ALL
SELECT 'S1V7021',621,'website','Gain'
Thank You so Much
[/INST]How about this query:
DECLARE @MYTABLE TABLE
(
ID VARCHAR (50),
distance INT,
ChannelSource VARCHAR (50),
REMARKS VARCHAR (50)
)
INSERT @MYTABLE
SELECT 'Z1G510A',719,'ThirdParty','Loss' UNION ALL
SELECT 'B18EAE2',91,'website',' Gain' UNION ALL
SELECT 'E116A40',451,'ThirdParty','Loss' UNION ALL
SELECT '91H8B6C',113,'ThirdParty','Loss' UNION ALL
SELECT 'S1Z165F',315,'ThirdParty','Loss' UNION ALL
SELECT 'F1D1308',983,'website','Loss' UNION ALL
SELECT '21577CA',1052,'website','Loss' UNION ALL
SELECT 'X1FF3A9',904,'website','Gain' UNION ALL
SELECT 'S1V7021',621,'website','Gain'
SELECT * FROM @MYTABLE
;WITH CTE AS
(
SELECT *,SUM(CASE WHEN REMARKS='Loss' THEN 1 ELSE 0 END)OVER(PARTITION BY 1)*1.0/COUNT(REMARKS)OVER(PARTITION BY 1) AS Probability_of_Loss
FROM @MYTABLE
)
UPDATE CTE
SET ChannelSource='website'
,REMARKS = CASE WHEN Probability_of_Loss > 0.5 THEN 'Gain' ELSE 'Loss' END
WHERE ID = 'Z1G510A'
SELECT * FROM @MYTABLE</s> |
<s>[INST]what are the pros and cons of a replicated database?
hi we run 2019 enterprise. Our new boss is wondering if a replicated oltp might solve some of out warehousing woes. she is probably thinking one of 2 things...1) start reporting off the replicated environment or 2) lessen the impact of reading from the oltp when loading the warehouse.
i worked once in an environment where the source data was from a replicated oltp. it didnt seem bad but from what i remember, if a column needs to be added to the oltp, the replicated table has to be rebuilt because the replicated environment has to match the source schema exactly. i dont recall if the same indexes have to be built in the replicated environ.
obviously oltp's arent shaped well for warehousing anyway so hopefully she is thinking more along the lines of #2.
I know cdc and other techniques are available for sourcing warehouses. So why would i want replication? [/INST]Your question is general and vague. There are many ways to skin this cat, and what is the best way depends on the circumstances.
Many people go with Availability Groups with readable secondaries, as this is also provides a HA/DR solution. I would also say that in comparison to Transactional Replication, they are easier to manage. But the distinct drawback is that the secondary is a 100% of the source database.
Transactional Replication has more moving parts, and as you mention schema changes require more planning. The upside is that the subscriber databases does not have to be 100% copies of the source, but you have more flexibility. For instance, you can have indexes in the subscriber to support reports that are not in the publisher, and thus does not slow down the OLTP business. And for matter you can also have less indexes if you are so inclined.
But while you have some flexibility, TR is probably not what you should go for if you want a completely different schema in the warehouse. As I said, there are many ways to skin the cat.</s> |
<s>[INST]Specifying failover 'order' within an Availability Group
We have been looking at two different setups and are trying to determine which will best suit our needs.
1) A single WSFC spread across 4 nodes (2 nodes in each of 2 data centers) and using a single AG comprising those 4 nodes.
2) Two WSFCs, one per data center, each containing 2 nodes, with an AG on each WFSC and then using a Distributed AG across the 2 WFSCs.
The problem with option 1 is the potential latency between the data centers. Yet, failover between all 4 replicas would be automatic.
The problem with option 2 is that failover from AG-1 on WSFC-1 to AG-2 on WSFC-2 must be manual and we prefer to not have to do manual failovers.
If we go with option 1, our preference would be that if node-1 at site-1 becomes unavailable, we prefer to first fail over to node-2 at site-1, and only fail to site-2 if nothing at site-1 is available. Is it possible to give replicas some sort of priority usage setting or some other way to do the failover the way we prefer?
Thanks
Sheila[/INST]How far apart are the data centres? I think I've seen 100 km quoted as the maximum distance for synchronous replication?
The common reason to have two data centres is to protect your business against major disasters like a data centre burning down or being hit a natural event like an earthquake or a hurricane. But for the latter, a 100 km distance is not a lot, and both data centres could easily be hit by the same natural disaster. Then again, this depends on where you are located. Here in Stockholm where I live, natural disasters are extremely unlikely.
Anyway, what I'm getting at, is that if your data centres are far apart, a distributed AG is your only choice.
You say that you would prefer having automatic failover to the other data centre, but how often do you think those failovers to happen? Does your primary centre do down often?</s> |
<s>[INST]SQL Server Deadlock Detection only kills one victim per each run?
My company has a production SQL Server 2019 Enterprise edition CU16. We found it has so many deadlocks that the oldest pair of deadlock processes have existed for one hour. I know SQL Server has an internal process called "deadlock detection" or "lock monitor", which periodically (as I know, runs every 5 secs) check for deadlock and automatically resolve deadlock by killing one of the deadlocked processes (the victim). My question is does this "deadlock detection" background process only kill one and only one victim each time it runs? So if there are so many concurrent deadlocks, then the detection process will not be fast enough to kill?[/INST]I've seen this. I recall, we had situations with, say, 12 processes in a deadlock. SQL Server selected one as a deadlock victim. Which left 11 processes deadlocked and so on.
It kind of make sense. With some luck, the deadlock will be really resolved. when you take out one of the players But there can also be other complications. Maybe there is some other processes that was blocked by the deadlock victim, but not part of the deadlock. That process can now proceed - but only to be entangled into that deadlock.
Note that if you have multiple deadlocks that are independent of each other, SQL Server on each round will kill one process in each deadlock.
Also, I believe that SQL Server may decrease that five-second interval if there are plenty of deadlocks and check for deadlocks more often. But when we had our 12-process deadlocks, that did not happen.</s> |
<s>[INST]Any risks/concerns kill in the middle long running SQL Agent backup job?
Hello, are there any risks/concerns kill in the middle long running SQL Agent backup job? (which I don't want to do but might be necessary in emergency situation)
Possible DB corruption or other negative impacts?
Realize one thing is it will take some time to rollback but other than that is it relatively safe?
Thanks in advance.[/INST]there is no negative impacts for this operation. It is safe. This is a backup operation not restore. If you kill a long running restore operation, then it will take some times to rollback.</s> |
<s>[INST]how to remove schemabinding from all functions and view in one go.
1\) I want to remove the schema binding from all my functions, then want to apply but in one go, how can it be done?
2\) I have few cols with columns in my database where collations is specified, i want to remove them in one go,
how both things can be done with few stmts?
[/INST]then want to apply but in one go, how can it be done?
You can't, there is no build-in function for it.
> where collations is specified, i want to remove them in one go,
You can't, there is no build-in function for it. Especially if the column is use i any index, all modification will fail.
The best option is to create a SSDT database project, import the database design, do the modification in the project and deploy the changes.</s> |
<s>[INST]Execution of Powershell script fails on SQL Agent
Hi,
I have developed a powershell script that calls an executable with a time limit of 15 minutes
To implement this I downloaded the package for the Start_threadjob from the powershell library. The script runs as expected when executing the script on the server from powershell or as compiled exe file
Code:
# execute program as thread job with a maximum run time of 15 minutes.
$ESDjob = Start-ThreadJob { & $using:prgPath @using:prgArgs}
But when I run this as a step of a SQL agent job, the error below is thrown:
The term 'Start-ThreadJob' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
I have other PS modules that I downloaded that can be executed as SQL agent. What could cause this issue?[/INST]The term 'Start-ThreadJob' is **not recognized as the name of a cmdlet,**
It's because it's not a default CmdLet available in a SQL Server-Agent job; you have to import the CmdLet in your script first.
But why, the job should already run as it's own thread, don't make much sense to use additional threading?</s> |
<s>[INST]MaxOf field & another field as single row
Hey
I cant seem to work this out... I have a table-
job_id
unit_id
part_id
version_id
timestamp
I need to get the timestamp by the Max of version_id using job_id, unit_id & part_id as filters. something like
SELECT Max(version_id) As MaxOfVersion, timestamp
FROM MyTable
WHERE job_id = 245 AND unit_id = 20 AND part_id = 1
I can do it by calling 2 queries but wondered if i could do it in one query? My 2 queries first get the MaxOfVersion as a single filed then use that to get as a parameter value to get the timestamp. Can it be incorporated into a single query?
Thanks
[/INST]Since you have a filter using job_id, unit_id & part_id, how about using TOP(1) along with ORDER BY instead of MAX() to get the max version_id. Check this:
SELECT TOP(1) version_id As MaxOfVersion,timestamp
FROM MyTable
WHERE job_id = 245 AND unit_id = 20 AND part_id = 1
ORDER BY version_id DESC</s> |
<s>[INST]DataGridView is empty after searching data in Database
xxxxxxxxxxxxx[/INST]string.Format("%(0)%", txtSuche.Text));
Do you know/have you tested, what that returns? It returns "%(0)%"; of cause that don't ends in a result.
You have to set the placeholder in curly brackets { } instead of rounds ( ) to get it working =\></s> |
<s>[INST]TLS related with Windows 2019 & SQL Server 2019 ?
Hello, sorry am confused.
My questions are how TLS corresponds within Windows Server 2019 on OS level & SQL Server 2019 installed on same VM.
Is TLS v1.0 & v1.1 disabled by default on both?
And TLS v1.2 is enabled by default on both?
What's the difference via the registry HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols and TLS listed in Web Browser settings?
Is it correct to say in example TLS v1.2 is enabled on Windows level but not on SQL Server level it would not allow SQL DB connection and vice versa?
Thanks in advance.[/INST]\> Windows Server 2019 currently TLS versions: 1.0 = Disabled, 1.1 = Disabled, 1.2 = Enabled Would a connection into SQL Server 2019 that's installed on same VM Windows Server 2019 mentioned above require only TLS v1.2 by default or would it allow all three (v1.0, v1.1, v1.2) from a remote client ?
According to your description, SQL server require only TLS 1.2 in this situation.</s> |
<s>[INST]add replica on different OS version
Hello,
We have a production instance running on SQL2014 on Win2012R2 with one AG replica on same version of OS. Now, we want to add one more replica on different server with Windows2019. Is it allowed to have a different version of OS among the replicas?
Thanks
[/INST]The OS version is for SQL Server / AG function intransparent (let say unknown/irrelevant), as long as it is a OS version supported by the used SQL Server version.</s> |
<s>[INST]dynamic sql not display is null issue ?
i work on sql server 2019 is null not display on dynamic sql
what i try is
declare @s2 varchar(max) = ''
set @s2 =--'select FROM Extractreports.dbo.FinalReportDashBoardNewReplacement WITH(NOLOCK)'
concat(
'select ',
STUFF((
SELECT ',' + ' + isnull(name,'') + '
FROM Extractreports.sys.columns
WHERE [object_id] = OBJECT_ID(N'Extractreports.dbo.FinalReportDashBoardNewReplacement')
FOR XML PATH('')
), 1, 1, ''),'FROM Extractreports.dbo.FinalReportDashBoardNewReplacement WITH(NOLOCK)')
select @s2
issue when see result it show as
select + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + , + isnull(name,'') + FROM Extractreports.dbo.FinalReportDashBoardNewReplacement WITH(NOLOCK)
i need instead of name column name display
but this not happen
[/INST]Try the following modifications:
1) Change `SELECT ',' + ' + isnull(name,'') + '` to `SELECT ',' + 'isnull(' + name + ','''') '`
2) Add one space before `FROM Extractreports.dbo.FinalReportDashBoardNewReplacement WITH(NOLOCK)` to avoid syntax error.
declare @s2 varchar(max) = ''
set @s2 =--'select FROM Extractreports.dbo.FinalReportDashBoardNewReplacement WITH(NOLOCK)'
concat('select ',
STUFF((
SELECT ',' + 'isnull(' + name + ','''') '
FROM Extractreports.sys.columns
WHERE [object_id] = OBJECT_ID(N'Extractreports.dbo.FinalReportDashBoardNewReplacement')
FOR XML PATH('')
), 1, 1, ''),' FROM Extractreports.dbo.FinalReportDashBoardNewReplacement WITH(NOLOCK)')
select @s2</s> |
<s>[INST]SQL Server 2014 is there any ways to improve bulk insert or bcp for large data sets from flat files or other methods that are faster?
Hello, for SQL Server 2014 is there any ways to improve bulk insert or bcp for large data sets from flat files or other methods that are faster?
Thanks in advance.
[/INST]Which is faster bulk insert or bcp and why?
I think you would need to run a benchmark to find out. I would expect performance to be about the same, but BULK INSERT uses OLE DB and BCP uses ODBC. And BULK INSERT is inside the engine, and BCP is a separate program. But it is also going to matter where the files are. What you should not to is to have the files on one machine, SQL Server on a second machine and run BCP from a third machine. But apart from that I would not make any guesses.
Simple or bulk-logged recovery should not matter that much. The same rules for minimally logged operations apply. TF 610 applies to plain INSERT statements in clustered indexes as I recall. With BCP/BULK INSERT you get minimally logged operations, as long as you use a hint to enforce tablock, as I recall.</s> |
<s>[INST]How to get data related from #parts table based on company id and in case of table #company not have companyid then display all data ?
I work on sql server 2019 i face issue
i need to write join display data from table #parts
based on values exist for #company in case of #company have companyid then get data related
if #company table not have any companyid then get all data from table #parts
create table #company
(
companyid int
)
insert into #company(companyid)
values
(1234)
create table #parts
(
PartId int,
CompanyId int
)
insert into #parts(PartId,CompanyId)
values
(1255512,1234),
(1255901,1234),
(1255541,1234),
(3050512,5591),
(3050913,5591),
(1255971,5591)
what i try
select p.partid,p.companyid from #parts p
inner join #company c on c.companyid=p.companyid
so if #company not have any company
then display all data on table #parts
if table #company have companyid then get companyid data related from table #parts
I need to do it on one statment please
so How to do it on one statment
[/INST]Do you mean?
select p.partid,p.companyid from #parts p
left join #company c on c.companyid=p.companyid</s> |
<s>[INST]When applying SQL Service Packs or Cumulative Updates have any of you experienced failure?
Hello, when applying SQL Service Packs or Cumulative Updates have any of you experienced failure?
(Is it possible applying above can cause SQL Server to not boot up or DBs corruptions, etc...?...just thinking of worst case scenarios)
If yes how do you rollback/troubleshoot or go abouts fixing/addressing it?
Thanks in advance.[/INST]there have occasionally been posts here in forums about errors when applying CUs. (Service Packs are a bit of the past now.)
The problem are of various kinds, but typically a failed application of a CU leaves you in a limbo, since you don't really know which state you are in.
And, yes, it can happen that SQL Server will not start, and you will get a very frightening error. Every application of a CU runs a script msdb110_upgrade.sql that runs various tasks in msdb and on server level. Unfortunately, there may be conditions on your server that causes the script to fail. There are some trace flags you can use to overcome the problem so that the server starts.
Other errors that can occur various components somehow not being aligned with each other. (I'm vague here, as I don't recall any exact case right now.)
On the other hand, database corruption is unlikely, I never heard of that. That said, you should always make sure that you have good backups of your databases. And you should also have good backups on Windows level. And if the VM is virtualised, taking a snapshot of the VM before you start is a good idea.</s> |
<s>[INST]How to give unque number to every different group of numbers ?
I work on sql server 2019 i face issue i need to give unique number to every group of numbers without using string aggreagte or stuff
**original table as below :**
create table #parts
(
PartNumber varchar(50),
PartValue int,
UniqueNumber int
)
insert into #parts(PartNumber,PartValue,UniqueNumber,UniqueNumber)
values
('P1',1,1),
('P1',2,1),
('P1',3,1),
('P1',4,1),
('P2',1,2),
('P2',2,2),
('P3',1,3),
('P3',2,3),
('P3',3,3)
SO IF ADD NEW PART P4 IT WILL get number 3 as it exist on original table
('P4',1,3),
('P4',2,3),
('P4',3,3)
and IF ADD NEW PART P5 IT WILL get number 2 as it exist on original table
('P5',1,2),
('P5',2,2)
and IF ADD NEW PART P6 IT WILL get number 4 max numbers for original table + 1
('P6',1,4),
('P6',2,4),
('P6',3,4),
('P6',4,4),
('P6',5,4)
so please how to solve it without using stuff numbers or string aggregate ?
**i don't need to use logic below because it will performance issue for big count **
may be using string aggreagte or stuff as 1,2,3 or 1,2 or 1,2,3,4
to get different between every group
but i don't need to use this logic by stuff or string aggreagte
[/INST]I update the code, and follow you logic step by step, please refer the code below:
create table #parts
(
PartNumber varchar(50),
PartValue int,
UniqueNumber int
)
insert into #parts(PartNumber,PartValue,UniqueNumber)
values
('P1',1,NULL),
('P1',2,NULL),
('P1',3,NULL),
('P1',4,NULL),
('P2',1,NULL),
('P2',2,NULL),
('P3',1,NULL),
('P3',2,NULL),
('P3',3,NULL),
('P4',1,NULL),
('P4',2,NULL),
('P4',3,NULL),
('P5',1,NULL),
('P5',2,NULL)
select PartNumber,sum(PartValue) as [GroupPartValueSum]
into #partvaluesum
from #parts
group by PartNumber
select p1.*,p2.GroupPartValueSum / PartValue as [PartValueDdivide]
into #result
from #parts as p1
left join #partvaluesum as p2
on p1.PartNumber = p2.PartNumber
select PartNumber,sum(PartValueDdivide) AS [PartValueDdivideSum]
into #tempresult
from #result
group by PartNumber
update r set r.UniqueNumber = t.PartValueDdivideSum
from #result as r
join #tempresult as t
ON r.PartNumber = t.PartNumber
select * from #result
drop table if exists #result
drop table if exists #tempresult
drop table if exists #partvaluesum
drop table if exists #parts
If right, please **Accept**.</s> |
<s>[INST]How to add a another column in the end from another table while using union all
Dear Experts,
I have a requirement to add another column from another temporary table to my query. It appears to work fine from within a single table. But could you please advise how I can get it work for another table. The query is below.
select L,O,GL,D,C,Des,
"Mapping"=case when GL like '%[_]%' then 'No Match' else 'Match' end
from #Final
union all
select '','','',sum(D),sum(C),'','' from #Final
[/INST]The SQL UNION ALL operator is used to combine the result sets of 2 or more SELECT statements. It does not remove duplicate rows between the various SELECT statements (all rows are returned).
Each SELECT statement within the UNION ALL must have the same number of fields in the result sets with similar data types.</s> |
<s>[INST]SQL Server 2022 expected release date?
We migrated our business solution from SQL Server 2017 to SQL Server 2022 CTP 2.0
Everything works well and im trying out some of the new features. Im very pleased, it was a smooth migration.
Does somebody has a hint, some information about the ETA of SQL Server 2022 RTM?
Kind regards
Paolo[/INST]Microsoft has made it very clear that they will respect the year. Thus, we can expect it to be released at latest 2022-12-31.
With experience from previous CTP programmes, I would expect a few more CTP 2.x, and then one or two RC before that.
But apart from that, your speculation is as good as mine. Microsoft does not announce release dates months in advance. Or even weeks. They release when it's ready.</s> |
<s>[INST]SQL Server Export and import BCP capture error and quit
Hi I am looking BCP exports/Imports to secondary server through a power shell user created tables for our ERP system
SQL version :2016 Enterprise
Windows 2019
problem description: I have created powershell script to export import user created tables using bcp utility. since its running though an script , I am looking to find how to quit(power shell script) the process when bcp process find an ERROR when its export /import data or any other way bcp can exit where there is an error ?
export
bcp sourcedatabase.dbo.table1 OUT \\networksharedata\bcp\table1.bcp -S servername -T -w -a 65535
import
bcp destination.dbo.table1 IN \\networksharedata\bcp\table1.bcp -f \\networksharedata\bcp\table1.fmt -S servername -T -a 65535
thanks
[/INST]Please add –e parameter in bcp command line.
**-e err_file**
Specifies the full path of an error file used to store any rows that the bcp utility cannot transfer from the file to the database. Error messages from the bcp command go to the workstation of the user. If this option is not used, an error file is not created.
If err_file begins with a hyphen (-) or a forward slash (/), do not include a space between -e and the err_file value.
As Olaf mentioned, the bcp will automatically exit when there is an error.</s> |
<s>[INST]Deletion of set of column values from all tables of all database in sql server 2020
CREATE TABLE INPUT_DRIVER
(SURR_KEY INT
)
CREATE TABLE ELEMENT
(
SURR_KEY INT,
FIRST_NAME VARCHAR (100),
MID_NAME VARCHAR (100),
LAST_NAME VARCHAR (100),
CITY VARCHAR (50),
STATES VARCHAR (50),
RACE_CODE INT, -- Need to Soft Delete
CHLD_NO INT, -- Need to Soft Delete
DOB DATE, -- Need to Soft Delete
INCM FLOAT,-- Need to Soft Delete
OCCUPATION VARCHAR (100) -- Need to Soft Delete
)
I have a Input Driver Table which contain only 1 column "Surr Key"
Based on the Surr Key I want to do soft delete ("replacing value with xxxx) for above mention column
from all Tables existing in any database or materialised views or any temporary table.
**Surrogate key will be same in all tables.**
Please help.
[/INST]There is no SQL Server 2020.
You can put xxxx in an int column. Or a date column. Or a float column.
Then again, why not simply set them to NULL?
UPDATE ELEMENT
SET RACE_CODE = NULL,
CHLD_NO = NULL,
DOB = NULL,
INCM = NULL,
OCCUPATION = NULL
FROM ELEMENT E
WHERE E.SURR_KEY IN (SELECT S.SURR_KEY FROM INPUT_DRIVER)</s> |
<s>[INST]find out the date to belong in which quarter by sql ,case 1 script
I have many different case, 1 of the case is here.the other case, will ask in another post.
I have a date (e.g. 2022-2-15 00:00:00:000), and I have amount in customer table
how can i find out a date belong to which quarter in 2022 ?
customer table (
customerid numeric,
policy_no varchar(16),
start_date SWDATE (datetime ),
amount numeric)
date field with datatype start_date , SWDATE (DATETIME)
AND I have a temp table (
customerid (numeric),
policy_no varchar(16),
start_date swdate(datetime),
Q1 NUMERIC,
Q2 NUMERIC,
Q3 NUMERIC
)
how can I find out the start_date is belong which and insert amount into that column. (q1,q2,or q3)
IF BELONG 2022 Q1, THEN INSERT AMOUNT TO Q1 COLUMN
ELSE IF
START DATE BELONG 2022 Q2, THEN INSERT AMOUNT INTO Q2 COLUMN
ELSE IF
START DATE BELONG 2022 Q3, THEN INSERT AMOUNT INTO Q2 COLUMN
ELSE
DO NOTHING
[/INST]Please check this sample:
create table customer(
customerid numeric,
policy_no varchar(16),
start_date datetime ,
amount numeric)
;
create table temp (
customerid numeric,
policy_no varchar(16),
start_date datetime,
Q1 NUMERIC,
Q2 NUMERIC,
Q3 NUMERIC,
Q4 NUMERIC
)
insert into customer values
(111,'aa','2022-2-15 00:00:00:000',1000),
(111,'aa','2022-5-15 00:00:00:000',2000),
(111,'aa','2022-8-15 00:00:00:000',3000),
(111,'aa','2022-11-15 00:00:00:000',4000)
select * from customer;select * from temp;
insert into temp
select customerid,policy_no,start_date
,case when datepart(QUARTER,start_date)=1 then amount else null end as Q1
,case when datepart(QUARTER,start_date)=2 then amount else null end as Q2
,case when datepart(QUARTER,start_date)=3 then amount else null end as Q3
,case when datepart(QUARTER,start_date)=4 then amount else null end as Q4
from customer
select * from temp;</s> |
<s>[INST]Divide by zero error encountered.
Error is generating ,when dividing by 0
Create table #Containerno (CID int,ConWEight varchar(50),Container_Rate decimal(10,4),Trucking_Charges decimal(10,4),)
insert into #Containerno values(444,' ', 22.01,5555)
SELECT convert(numeric(10,2),(isnull(nullif(c.ConWeight,''),0)*c.Container_Rate)+c.Trucking_Charges)/isnull(nullif(c.ConWeight,''),0) as Invoice_Amount
FROM #Containerno c
[/INST]As we all know: the divisor cannot be zero.
So when ConWeight is ' ', the divisor will be zero. Therefore, you could do this modification:
SELECT convert(numeric(10,2),(isnull(nullif(c.ConWeight,''),0)*c.Container_Rate)+c.Trucking_Charges)/isnull(nullif(c.ConWeight,''),1) as Invoice_Amount
FROM #Containerno c</s> |
<s>[INST]How to intercept the fields I want from my table
Hi,experts
I have many columns in my table and the data in one column is very verbose, how can I truncate the data I want?
What are the more commonly used string functions in sqlserver?
Thanks,any suggestion will do
I have three columns in my table, one of which contains the student's name and date and the type of assignment submitted, and I need to split them out and find the highest score for their assignment. I have pasted my table structure and the results I want below, thanks in advance guys.
CREATE TABLE Homeworkdetails(
[id] int not null,
[HomeworkName] varchar(50),
[Score] [int]
)
INSERT into Homeworkdetails([id], [HomeworkName], [Score]) VALUES
(1,'Lynn_20220913.doc', 70),
(2,'Lynn(2)_20220914.doc',85),
(3,'Denial_20220913.txt',85),
(4,'Denial_and_Gullen20220914.doc',100),
(5,'Gullen_20220914.txt',88),
(6,'Gullen(2)_20220914.txt',90),
(7,'Lynn_and_Gullen20220914.txt',70),
(8,'Danking_20220912.txt',85),
(9,'Danking(2)_20220913.txt',90)
name date type score
Lynn 2022-09-14 doc 85
Denial 2022-09-13 txt 85
Denial_and_Gullen 2022-09-14 doc 100
Gullen 2022-09-14 txt 90
Lynn_and_Gullen 2022-09-14 txt 70
Danking 2022-09-13 txt 90[/INST]Try this code:
CREATE TABLE Homeworkdetails(
[id] int not null,
[HomeworkName] varchar(50),
[Score] [int]
)
INSERT into Homeworkdetails([id], [HomeworkName], [Score]) VALUES
(1,'Lynn_20220913.doc', 70),
(2,'Lynn(2)_20220914.doc',85),
(3,'Denial_20220913.txt',85),
(4,'Denial_and_Gullen20220914.doc',100),
(5,'Gullen_20220914.txt',88),
(6,'Gullen(2)_20220914.txt',90),
(7,'Lynn_and_Gullen20220914.txt',70),
(8,'Danking_20220912.txt',85),
(9,'Danking(2)_20220913.txt',90)
name date type score
Lynn 2022-09-14 doc 85
Denial 2022-09-13 txt 85
Denial_and_Gullen 2022-09-14 doc 100
Gullen 2022-09-14 txt 90
Lynn_and_Gullen 2022-09-14 txt 70
Danking 2022-09-13 txt 90
;with cte as
(
select *
,REPLACE(RTRIM(REPLACE(SUBSTRING([HomeworkName],0,patindex('%[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%',[HomeworkName])),'_',' ')),' ','_') +'(' as [name]
,CAST(SUBSTRING([HomeworkName],patindex('%[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%',[HomeworkName]),8) as date) as [date]
,SUBSTRING([HomeworkName],CHARINDEX('.',[HomeworkName])+1,LEN([HomeworkName])-CHARINDEX('.',[HomeworkName]))as [type]
,score as [score2]
from Homeworkdetails
)
,cte2 as (
select SUBSTRING([name],0,CHARINDEX('(',[name])) as [name]
,[date]
,[type]
,[score] from cte
)
,cte3 as (
select [name]
,[date]
,[type]
,[score]
,ROW_NUMBER()over(partition by name order by score desc) as nn from cte2
)select [name],[date],[type],[score] from cte3 where nn=1</s> |
<s>[INST]UPDLOCK to handle deadlocks
What should we do in the queries to handle deadlocks? Is UPDLOCK a way to go?[/INST]Deadlocks are normal and expected in a multi-user system. There is always a chance multiple users/processes may be trying to update the same record. The victim should be coded to retry on deadlock error.</s> |
<s>[INST]Calculating What Percentage Value Of Top Five Records From A Single Column
Hello! I have a column of numbers and want to calculate in SSMS what percentage of the whole the top five make up. In Excel the answer I got back was 89.99619%
I then want to concat that value to a sentence, so my final output would be "The top five records count for 89.99619% of the total", or something like that.
I cannot figure out how to get the top five values without using order by, which I know is not allowed in a subquery. Thank you all for looking at this matter for me.
Here are my values...
1502359.92
974102.52
144425.43
138021.46
101418.03 \<-- this is the last of the top five
79395.06
78987.63
66347.38
46811.04
24318.51
22089.14
[/INST]Select *, concat('The top five records count for ',format(percentOfTop5,'P4'),' of the total ',total)
from (
select num,
row_number() Over( order by num desc) rn,
Cast(SUM(num) OVER(ORDER BY num desc)*1.0 /SUM(num) Over () as decimal(18,6)) AS percentOfTop5
,SUM(num) Over () total
from testNum
) t</s> |
<s>[INST]Upgrade a SQL Server failover cluster from SQL Server 2017 to SQL Server 2019 and applying a Cumulative update simultaneously
Hi All,
Current:
- Microsoft SQL Server 2017 (RTM-CU20) (KB4541283) - 14.0.3294.2 (X64) Mar 13 2020 14:53:45 Copyright (C) 2017 Microsoft Corporation Enterprise Edition: Core-based Licensing (64-bit) on Windows Server 2016 Standard 10.0 <X64> (Build 14393: ) (Hypervisor)
We are planning on upgrading a 2 node SQL Server Failover Cluster to SQL Server 2019. We would like to minimize the downtime to a single reboot. Our plan is as follows:
1. Upgrade the Passive HOST1 from 2017 to 2019
2. Apply Cumulative Update 18 to HOST1
3. Initiate Upgrade on Active HOST2 -- midway thru, setup will cause automatic failover to Passive HOST1 -- database upgrade will occur. HOST1 becomes Active. HOST2 becomes passive
4. Complete upgrade on HOST2
5. Apply Cumulative Update 18 to HOST2.
Question: can I apply the Cumulative Update (Step 2), before initiating the upgrade on the Active host (Step 3) ??? A yes answer means we only go through one reboot.
Thanks for any help you can provide.
\--Dan
[/INST]your process looks good, i would recommend two things.
complete Step 1 and 2 on Host1, then reboot that node - finished
Step 3 - manually failover your instance via Failover Cluster Manager... it will move your resources and upgrades the databases
then complete Step 4 and 5 on Host2, reboot and done.
Do NOT rely on the upgrade process to move your resources... do it on your own.
And you have to apply the CU before moving the resources on Host1!</s> |
<s>[INST]SQL 2019 SQLBrower.exe
I have a 3 node active, active passive cluster running a variety of SQL Editions, 2014 up to 2016. Recently I installed SQL 2019 (CU17) and the SQLBrowser service although running was not working. No firewall, no blocked port, no missing SQLBrowser.exe file, Service running fine (checked on SQL Admin and Windows Services), nodes rebooted BUT my apps could not now connect to a named instance without stating the port number - before they could.
After much investigation I resolved the issue - the version of the SQLBrowser.exe file had changed. I stopped the service running, made a backup of the sqlbrowser.exe file and copied a version over from another cluster that did not have 2019 installed. Restarted services and bingo all back up and running.
Really strange are you aware of the sqlbrowser.exe file being updated and preventing it working after a 2019 installation?
More testing required but is it possible to install SQL 2019 without installing the SQL Browser service?[/INST]\> My question/issue refers to a cluster running multiple versions of SQL Server, i.e. 2016, 17 and 19. Is this not best practice and not supported?
Yes, one SQL FCI with different version SQL server is not best practice. Please make sure the SQL server instances are added to one SQL cluster have the same version.</s> |
<s>[INST]The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
**The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.**
i get the error can you help me?
[/INST]As experts answered, just remove the ORDER BY clause in views, inline functions, derived tables, subqueries, and common table expressions.
Or, as the error message said, specify TOP like this: `SELECT TOP (100) PERCENT ... FROM ... ORDER BY column ` or OFFSET like this: `ORDER BY column DESC OFFSET 0 ROWS`. However, both seems meaningless to me.</s> |
<s>[INST]How to pull 10 last record of a user who have more than 10records
hello.
I have 2 tables connected with each other, for simplicity lets say ID of the 1st is connected to UserCreated_FK of the 2nd table.
table A:
| ID | NAME |
| 237| Gal |
| 240| blah |
| 250| blah2|
in the parallel table ( aka table B ) I have the following:
| UserCreated_FK | col2|
| 237 | 10/10|
| 237 | 19/10|
(10more records no.237|
| 240 | 11/10|
(7more records no.240|
| 250 | 12/10|
(11more records no.250|
and other columns aswell. for showcasing I made it only two.
**Wanted result:**
| ID | NAME | Col2
| 237| Gal | 10/10
| 237| Gal | 10/10
| 237| Gal | 10/10
| 237| Gal | 10/10
| 237| Gal | 10/10
| 237| Gal | 10/10
| 237| Gal | 10/10
| 237| Gal | 10/10
| 237| Gal | 10/10
| 237| Gal | 10/10
| 250| blah2| 12/10
| 250| blah2| 12/10
| 250| blah2| 12/10
| 250| blah2| 12/10
| 250| blah2| 12/10
| 250| blah2| 12/10
| 250| blah2| 12/10
| 250| blah2| 12/10
| 250| blah2| 12/10
| 250| blah2| 12/10
My task is to check which of those IDs(person'sIds) have more then 10 records on table B ( because table A is just the ids and names not the actual records of them. so for example,
ID no.237 got 19records on table B I want to be able to pull the last 10 records of that user.
and again, the condition is only users that have more than 10 records, then to pull the last of 10 of those..
(10 **LAST** records of each ID( in my original table I have date so can be sorted by date )
Hope I was understandable, thanks a lot, any help will be appreciated!
[/INST]Two ways to skin the cat:
WITH numbering AS (
SELECT userid, col2, row_number() OVER(PARTITION BY userid ORDER BY col2) AS rowno
FROM tbl
)
SELECT userid, col2
FROM tbl
WHERE rowno <= 10
SELECT u.userid, t.col2
FROM users u
CROSS APPLY (SELECT TOP (10) t.col2
FROM tbl t
WHERE u.userid = t.userid
ORDER BY t.col2) AS t
The latter solution assumes that you have a users table.
Which of these two that is the best depends on the profile of the data. If there can be thousands of rows for the same user, the second is likely to perform better. On the other hand, if users typically have 5-20 rows, the first one may be faster.</s> |
<s>[INST]old data of history table not removed after enabling retention period
I enabled the retention period for existing history table and set the period to 90 days.
Then I ran the job syspolicy_purge_history but the data was not removed.
What are the things needed to be done for this?[/INST]To my knowing, syspolicy_purge_history has nothing to do with temporal tables. I believe this job is for purging the history for Policy-Based Management, a fairly unknown and not very widely used feature in SQL Server.
The purge of a history table is performed by a background task, and I don't think there is a way to run this manually.
Also, keep in mind that if you set a retention period to 90 days, this means that rows that ceased to be current 90 days ago will be removed from the the history table. But a row that was created three years ago and still valid, remain in the table. Likewise if it was changed as late as yesterday.</s> |
<s>[INST]MS-SQL Query for counting identity existing an another column
Trying to find the proper Query to get the SUM of iteration in a table
Column Id > GUID Column OrgId > GUID | GUID | GUID Etc.....
ID OrgId
a1 a1 >> Master Organisation
a2 a1 | a2 Child of a1 Master
a3 a1 | a2 | a3 Child of a2
a4 a1 | a2 | a3 | a4 Child of a3
a5 a1 | a2 | a3 | a5 Child of a3
a6 a1 | a2 | a3 | a6 Child of a3
If need to get the following (number of time this ID is present IN OrgID)
a1 >> 6 (is 6 time)
a2 >> 5 (is 5 time)
a3 >> 4 (is 4 time)
a4 >> 1 (is 1 time)
a5 >> 1 (is 1 time)
a5 >> 1 (is 1 time)
SELECT Count(*) as c FROM MyTable WHERE OrgId LIKE '%'+ Id +'%'
The result just return 1 for each group instead of 6,5,4,1,1,1
Thanks for the help
[/INST]Try this:
SELECT s.value, COUNT(*)
FROM tbl t
CROSS APPLY string_split(t.OrgID, '|') AS s`
GROUP BY s.value
Note: had you provided table and data as CREATE TABLE + INSERT, I would have been able to test my solution. This is an untested solution.</s> |
<s>[INST]Want to disable rounding in SSMS settings
Is there a way to disable numeric rounding for the query results in my SSMS settings? For example, my query returns a value of 2.6. This is misleading because when I export the results to a flat file, the value is 2.55555555555. I would like to know this what my client will see on the file I send them so that I can fix it in the query.
I am using Windows 10 Enterprise OS Build 19044.2130 64 bit & SSMS v18.12.1.
[/INST]To adjust the behaviour, try this query in SSMS:
select format(NumericValue, 'G17')
from ███████
Do not use the *format* function in SSIS if not needed.</s> |
<s>[INST]Can't figure out why The select list for the INSERT statement contains fewer items than the insert list
Hi everyone,
I want to create a stored procedure that will create a table and return value, but I got this message:
Msg 120, Level 15, State 1, Procedure sp_Month01_FYCalendar, Line 36 [Batch Start Line 9]
The select list for the INSERT statement contains fewer items than the insert list. The number of SELECT values must match the number of INSERT columns.
I tried adding, deleting, removing and always the must match error, can someone please help, here is the SQL query:
USE [ACR_Accounting]
GO
/****** Object: StoredProcedure [dbo].[sp_Month01_FYCalendar] Script Date: 2022-11-11 5:15:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sp_Month01_FYCalendar]
@startDate DATE, -- the start of the date range
@endDate DATE -- the end of the date range
AS
BEGIN
SET NOCOUNT ON;
DECLARE @fiscalOffset int = -1;
if (@startDate > @endDate)
BEGIN
DECLARE @temp date = @startDate;
SET @startDate = @endDate;
SET @endDate = @temp;
END
IF OBJECT_ID('dbo.Month01_FYCalendar') IS NOT NULL
DROP TABLE Month01_FYCalendar
CREATE TABLE Month01_FYCalendar
(
CalendarID int identity(1,1) not null
,FiscalDate date not null
,FiscalYear int not null
,FiscalMonth int not null
,FiscalQuarter int not null
,FiscalJulianDay int not null
,MonthName nvarchar(15) not null
,DayOfMonth int not null
,WeekDayNumber int not null
,WeekDayName nvarchar(15) not null
)
;WITH m AS
(
SELECT TOP (DATEDIFF(Month, @startDate, @endDate) + 1) m = ROW_NUMBER() OVER (ORDER BY [object_id])
FROM sys.all_objects
)
INSERT INTO Month01_FYCalendar
(
--CalendarID
FiscalDate
,FiscalYear
,FiscalMonth
,FiscalQuarter
,FiscalJulianDay
,MonthName
,DayOfMonth
,WeekDayNumber
,WeekDayName
)
SELECT CONVERT(VARCHAR, DATEPART(YEAR, DATEADD(Month, m-1, @startDate))) + CONVERT(VARCHAR, DATEPART(MONTH, DATEADD(Month, m-1, @startDate))),
DATEDIFF(MONTH, @startDate, DATEADD(Month, m-1, @startDate)) + 1
FROM m;
;WITH n AS
(
SELECT TOP (DATEDIFF(DAY, @startDate, @endDate) + 1) n = ROW_NUMBER() OVER (ORDER BY [object_id])
FROM sys.all_objects
)
SELECT n as [rownumber]
,DATEADD(DAY, n-1, @startDate) AS FiscalDate
,DATEPART(YEAR, DATEADD(DAY, n-1, @startDate)) AS FiscalYear
,DATEPART(MONTH, DATEADD(DAY, n-1, @startDate)) AS FiscalMonth
,DATEPART(QUARTER, DATEADD(DAY, n-1, @startDate)) AS FiscalQuarter
,DATEPART(DAYOFYEAR, DATEADD(DAY, n-1, @startDate)) As FiscalJulianDay
,DATENAME(MONTH, DATEADD(DAY, n-1, @startDate)) AS [MonthName]
,DATEPART(DAY, DATEADD(DAY, n-1, @startDate)) AS [DayOfMonth]
,DATEPART(WEEKDAY, DATEADD(DAY, n-1, @startDate)) AS WeekDayNumber
,DATENAME(WEEKDAY, DATEADD(DAY, n-1, @startDate)) AS WeekDayName
FROM n
END
GO
[/INST]CREATE PROCEDURE [dbo].[sp_Month01_FYCalendar]
@startDate DATE, -- the start of the date range
@endDate DATE -- the end of the date range
AS
BEGIN
SET NOCOUNT ON;
DECLARE @fiscalOffset int = -1;
if (@startDate > @endDate)
BEGIN
DECLARE @temp date = @startDate;
SET @startDate = @endDate;
SET @endDate = @temp;
END
IF OBJECT_ID('dbo.Month01_FYCalendar') IS NOT NULL
DROP TABLE Month01_FYCalendar
CREATE TABLE Month01_FYCalendar
(
CalendarID int identity(1,1) not null
FiscalDate date not null
,FiscalYear int not null
,FiscalMonth int not null
,FiscalQuarter int not null
,FiscalJulianDay int not null
,MonthName nvarchar(15) not null
,DayOfMonth int not null
,WeekDayNumber int not null
,WeekDayName nvarchar(15) not null
)
;WITH m AS
(
SELECT TOP (DATEDIFF(DAY, @startDate, @endDate) + 1) n = ROW_NUMBER() OVER (ORDER BY [object_id])
FROM sys.all_objects
)
INSERT INTO Month01_FYCalendar
(
--CalendarID
FiscalDate
,FiscalYear
,FiscalMonth
,FiscalQuarter
,FiscalJulianDay
,MonthName
,DayOfMonth
,WeekDayNumber
,WeekDayName
)
SELECT DATEADD(DAY, n-1, @startDate) AS FiscalDate
,DATEPART(YEAR, DATEADD(DAY, n-1, @startDate)) AS FiscalYear
,DATEPART(MONTH, DATEADD(DAY, n-1, @startDate)) AS FiscalMonth
,DATEPART(QUARTER, DATEADD(DAY, n-1, @startDate)) AS FiscalQuarter
,DATEPART(DAYOFYEAR, DATEADD(DAY, n-1, @startDate)) As FiscalJulianDay
,DATENAME(MONTH, DATEADD(DAY, n-1, @startDate)) AS [MonthName]
,DATEPART(DAY, DATEADD(DAY, n-1, @startDate)) AS [DayOfMonth]
,DATEPART(WEEKDAY, DATEADD(DAY, n-1, @startDate)) AS WeekDayNumber
,DATENAME(WEEKDAY, DATEADD(DAY, n-1, @startDate)) AS WeekDayName
FROM m
END</s> |
<s>[INST]How to increase size of nvarchar(max) in sql server ms
Let us assume a table with below definition:
Create table demo (json_data nvarchar(max));
I loaded the json format data into this for a row. The data was too large.
While loading the data using insert statement, I didn't receive any error. BUT while accessing the data using 'Select json_data from demo' , I found that the json_data has been trimmed and shows only initial 65536 characters.
Is the a way by which we can enhance the size ?
# data_type \#sql \#size
[/INST]If you get the correct length using *select len(json_data) from demo*, then the data are not truncated.
Probably the program that is used in your test shows the partial result. In case of Management Studio, see menu, Tools, Options, Query Results, SQL Server, Results to Grid.</s> |
<s>[INST]Long running queries which takes more than 10 seconds in last 7 days
Hello,
How can we find database wise long running queries which takes more than 10 seconds in last 7 days?
Thanks in advance.[/INST]The query that Ronen gave you only lists information from the plan cache. This means that it will not include queries that have fallen out of the cache - or never were put in the cache in the first place. Also, if the server was restarted yesterday, you cannot go back a week.
If you have enabled Query Store for your database, your are in a better position. Query Store has a wealth of data, and there are a number of ways to slice and dice it, depending on what you are looking for. Below is a sample query. I added CPU time, since Ronen made a very good comment about that.
SELECT qt.query_sql_text, SUM(rs.count_executions) AS TotalExedCount,
SUM(rs.avg_duration*rs.count_executions / 1000) AS TotalDurationInMs, MAX(rs.max_duration / 1000) maxdurinms,
SUM(rs.avg_cpu_time * rs.count_executions / 1000) AS TotalCpuInMs, MAX(rs.max_cpu_time / 1000) maxCpuinms
FROM sys.query_store_query_text qt
JOIN sys.query_store_query q ON qt.query_text_id = q.query_id
JOIN sys.query_store_plan p ON q.query_id = p.query_id
JOIN sys.query_store_runtime_stats rs ON p.plan_id = rs.plan_id
JOIN sys.query_store_runtime_stats_interval rsi ON rs.runtime_stats_interval_id = rsi.runtime_stats_interval_id
WHERE rsi.start_time > dateadd(DAY, -7, sysdatetimeoffset())
GROUP BY qt.query_sql_text
HAVING MAX(rs.max_duration / 1000) > 10000
Note: Query Store was introduced in SQL 2016.</s> |
<s>[INST]Does SQL Server Express use MDF & NDF as the data file?
Hi,
I use many version of SQL Server, including 2012, 2008, 2008R2. But have no experiences with SQL Server Express.
Does SQL Server Express also use MDF & NDF as the data file? And whether such data file can be used in SQL Server directly?
Thank you
[/INST]SQL Server Express Edition uses the same database engine as other editions. The storage architecture is the same, with data stored in data files along and a transaction log too. These files are maintained exclusively by the database engine.</s> |
<s>[INST]Trying to get the previous years values
In my erp I am making a query to get the previous year sales. I was thinking of using the datediff function.
I would use the field docdate and write something like this in the ERP. DocDate >= 'YYYY-01-01' AND DocDate <= 'YYYY-12-31'
Want to return DocDate >= '(YYYY-1)-01-01' AND DocDate <= '(YYYY-1)-12-31'[/INST]If your parameter is just represent year,and the type of it is integer,then your code should be like this :
docdate >= datefromparts([%0] - 1, 1, 1) and
docdate <= datefromparts([%0] - 1, 12, 31)</s> |
<s>[INST]row total sql showing null
Hello
This is my code
CREATE TABLE #RPT_DailySalesSummary (
CalDate DATE
,OrderID VARCHAR(10)
,SalesAmount INT
,LocRecID INT
)
INSERT INTO #RPT_DailySalesSummary
SELECT '2016-12-01', 'R101', 100, 81
UNION ALL
SELECT '2016-12-01', 'R102', 120, 81
UNION ALL
SELECT '2016-12-01', 'R113', 150, 82
UNION ALL
SELECT '2016-12-01', 'R104', 130 , 85
UNION ALL
SELECT '2016-12-02', 'R205', 250 , 81
UNION ALL
SELECT '2016-12-02', 'R106', NULL, 82
UNION ALL
SELECT '2016-12-02', 'R112', NULL, 85
UNION ALL
SELECT '2016-12-02', 'R032', 80 , 85
delete from #RPT_DailySalesSummary
DECLARE @cols NVARCHAR(MAX)=''
DECLARE @query NVARCHAR(MAX)=''
DECLARE @COLS_SUM NVARCHAR(MAX)=''
DECLARE @COLS_TOT NVARCHAR(MAX)=''
--Preparing columns for Pivot
SELECT @cols = @cols + QUOTENAME(LocRecID) + ','
FROM (SELECT DISTINCT LocRecID FROM #RPT_DailySalesSummary ) AS tmp
SELECT @cols = SUBSTRING(@cols, 0, LEN(@cols))
--Preparing sum of columns for Totals Horizontal
SELECT @COLS_SUM = @COLS_SUM + QUOTENAME(LocRecID) + '+'
FROM (SELECT DISTINCT LocRecID FROM #RPT_DailySalesSummary ) AS tmp
SELECT @COLS_SUM = ','+ SUBSTRING(@COLS_SUM, 0, LEN(@COLS_SUM)) +' AS TOTAL'
--Preparing sum of individual columns for Totals Vertically
SELECT @COLS_TOT = @COLS_TOT +'SUM('+ QUOTENAME(LocRecID) + '),'
FROM (SELECT DISTINCT LocRecID FROM #RPT_DailySalesSummary ) AS tmp
SELECT @COLS_TOT = SUBSTRING(@COLS_TOT, 0, LEN(@COLS_TOT))
SET @query =
'SELECT *'+@COLS_SUM+' INTO #TAB FROM
(
SELECT CalDate, SalesAmount, LocRecID
FROM #RPT_DailySalesSummary
) src
PIVOT
(
SUM(SalesAmount) FOR LocRecID IN (' + @cols + ')
) piv
SELECT * FROM #TAB
UNION ALL
SELECT NULL AS TOTAL ,'+@COLS_TOT+',SUM(TOTAL) FROM #TAB
'
execute(@query)
It showing Resultset Row Total As NULL
How to do row total even if its null
Thanking You
[/INST]Try replacing the line 38 with:
`SELECT @COLS_SUM = @COLS_SUM + ' isnull(' + QUOTENAME(LocRecID) + ', 0) +' `</s> |
<s>[INST]CTE with TEMP table
What are the other ways to achieve the below results?
-- Run pre-results and store it in temp table
CREATE TABLE #TEMP_SAVE (USERID VARCHAR(100))
INSERT INTO #TEMP_SAVE
SELECT USERID FROM IMSIDENTITYPRE
EXCEPT
SELECT USERID FROM PPPRETEST
-- Run Post results and filter results out with TEMP_Save results
;WITH CTE(USERID)
AS
(SELECT ims.USERID FROM IMSIdentityPOST ims
EXCEPT
SELECT pp.USERID FROM PPposttest pp)
SELECT * FROM CTE WHERE USERID IN (SELECT USERID FROM #TEMP_SAVE)
[/INST]Rather than using the temp table, you could have two CTEs:
;WITH CTE(USERID) AS (
SELECT ims.USERID FROM IMSIdentityPOST ims
EXCEPT
SELECT pp.USERID FROM PPposttest pp
, TEMP_SAVE(USERID) AS (
SELECT USERID FROM IMSIDENTITYPRE
EXCEPT
SELECT USERID FROM PPPRETEST
SELECT * FROM CTE WHERE USERID IN (SELECT USERID FROM TEMP_SAVE)
You could also make use of the INTERSECT operator:
(SELECT ims.USERID FROM IMSIdentityPOST ims
EXCEPT
SELECT pp.USERID FROM PPposttest pp
INTERSECT
(
SELECT USERID FROM IMSIDENTITYPRE
EXCEPT
SELECT USERID FROM PPPRETEST</s> |
<s>[INST]Select maximum of update number in all vouchers
Hi,
I need all vouchers in maximum of update number.
create table #temp (_Type varchar(20),_Voucher varchar(20),_Update int)
insert into #temp (_Type,_Voucher,_Update) values ('AAA','1001',1), ('AAA','1001',2), ('AAA','1001',3),
('BBB','1001',1), ('BBB','1001',2), ('BBB','1001',3),('CCC','1001',1), ('CCC','1001',2), ('CCC','1001',3)
select * from #temp
drop table #temp[/INST]If I understand correctly, you can try this query.
select * from
(select *,max(_Update)over(partition by _Type) as maximum from #temp) as t
where _Update = maximum;</s> |
<s>[INST]Move a very big table from Primary filegroup to another filegroup
Hi,
I have a very big table ..lets name it table1 approx 5 TB all in primary filegroup. I am planning to separate the IN_ROW, ROW-OVERFLOW and LOB pages to separate data files in a secondary file group.
Since the table is very huge, I am not going to attempt Index rebuild approach. I am thinking of below approach
1) Create a new file groups and data files
2) script out table1 schema and create a new table table1_new with the the clustered index in new secondary filegroups
3) create a script that will copy records from table1 to table1_new in batches. This script will be running all the time to copy data to table1_new
4) Find a way to send the updates and deletes to table1 to table1_new till the cutover day.
I cant think of a way how to achieve Step 4. Transactional replication and CDC would require that I initialize table1_new before I could start the sync which is not a suitable option in my case.
Is there a way I can achieve it with the help of triggers or any other mechanism that ensures that if an update statement executes in table1, the logic captures the Update statement checks for the existence of that record in table1_new based on the ID value and updates the record. If the record has not yet been copied to table1_new , discard it.
Thanks
[/INST]It can certainly be done, and in more than one way. An MVP colleague told me that he had implemented exactly this for a schema change. I seem to recall that he set up a view over both tables, and had INSTEAD OF triggers to update both tables.
It could be done with AFTER TRIGGERS as well. Or it could be done asynchronously with help of Change Tracking (which is a lot more lightweight than CDC.)
The challenge here, though, is that whichever method you employ, you need to understand it well, so that you don't lose data due to a programming error, or because your overlook a situation that could occur. It definitely counts as an advanced operation.
Which version and edition of SQL Server do you have? I would assume that with such a big table, you have Enterprise Edition. And if you have a version recent enough, you could use resumable index rebuild to move the table. This will use batching behind the scenes, although you don't have control over the batch size. But it is far less risky than rolling your own.</s> |
<s>[INST]Convert INT year and month to a DATE
Hi,
I have a field (closing_date) which is formatted as yyyymm and stored as an INTEGER. Is there anyway I can convert this into a DATE, ideally into this format yyyy-mm-dd?
Many thanks[/INST]select CAST(concat(202212,'01') as date)</s> |
<s>[INST]Backup failed in sql databases
Executing the query "DBCC CHECKDB(N'DB') WITH NO_..." failed with the following error: "A database snapshot cannot be created because it failed to start.
A database snapshot cannot be created because it failed to start.
Cannot create file 'G:\\DATA\\DB_Data.MDF_MSSQL_DBCC11' because it already exists. Change the file path or the file name, and retry the operation.
The database snapshot for online checks could not be created. Either the reason is given in a previous error or one of the underlying volumes does not support sparse files or alternate streams. Attempting to get exclusive access to run checks offline.
The database could not be exclusively locked to perform the operation.
Check statement aborted. The database could not be checked as a database snapshot could not be created and the database or table could not be locked. See Books Online for details of when this behavior is expected and what workarounds exist. Also see previous errors for more details.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
[/INST]The title says Backup, but it appears that you have a problem with DBCC CHECKDB?
DBCC CHECKDB creates a hidden database snapshot. Apparently this is failing here. It seems that there is a leftover file from a previous execution that was aborted for some reason. I would try to delete the file in the error message and try again.</s> |
<s>[INST]SQL agent job for TSQL Script fails to run
Hi
We have scheduled a TSQL Statement to update a field in parameter table last midnight.
The owner of this job is "sa"
However, we observe that the job wasn't run as scheduled. Nothing in "View History" nor log file. On the other hand, daily database maintenance job ran successfully last night (Maintenance job finished at around 9:00pm and thus not affecting the update job).
Is there any suggestion?
[/INST]make sure that the job is enabled and the schedule is also enabled</s> |
<s>[INST]MSSQL Performance monitoring
Any suggestions on enbale MSSQL perf monitoring. Including resource consumption and slow query? Also any MS recommended tools?[/INST]To an employee I just can recommend that you can also use the windows performance monitor, which can help you better understand the situation about SQL. We are not allowed to recommend third-part tools. Wish you good luck !</s> |
<s>[INST]PS: To perform operations you must run an elevated Windows PowerShell console.
Executed as user: NT Service\SQLSERVERAGENT. A job step received an error at line 1 in a PowerShell script. The corresponding line is 'Install-WindowsUpdate -MicrosoftUpdate -AcceptAll'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'To perform operations you must run an elevated Windows PowerShell console. '. Process Exit Code -1. The step failed.[/INST]But I must make sure some other maintenance work are done to start this work, like shrink and back up db, the windows task scheduler doesn't know it's done or not.
Just create an empty flag file in your SQL tasks when you start the backup and then delete the file when the backup is complete.
Have the task scheduler run a PS script that looks for the flag file and just waits until it is deleted.
$FlagFile = "c:\Data\SQL-maintenance-is-running.flg"
$Wait = $true
while ($Wait) {
if (Test-Path $FlagFile) {
Start-Sleep -Seconds 5 # the file exists, SQL is running its backup
# todo; add code to limit how long we should wait before notifying someone that
# there might be a problem with the backup.
} else {
$Wait = $false # backup is no longer running, install patches
}
}
# todo: maybe stop the SQL services here so that no additional SQL Agent tasks can start.
Install-WindowsUpdate -MicrosoftUpdate -AcceptAll
# todo: maybe force a reboot here to insure a clean boot and restart all SQL processes.
Run the SQL tasks as the SQL Agent, and the task scheduler task as the SYSTEM account.</s> |
<s>[INST]How I do serialize the data table into XML?
Hi.
I have an issue while to try convert data table into XML format
Error is "Cannot serialize the DataTable. DataTable name is not set".
What I tried is below
Public Function ConvertDatatableToXML(ByVal dt As DataTable) As String
Dim str As MemoryStream = New MemoryStream()
dt.WriteXml(str, True)
str.Seek(0, SeekOrigin.Begin)
Dim sr As StreamReader = New StreamReader(str)
Dim xmlstr As String
xmlstr = sr.ReadToEnd()
Return (xmlstr)
End Function
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim dt As DataTable = New DataTable()
dt = GetData()
Dim XMLstring As String = clsAPI.ConvertDatatableToXML(dt)
Me.txtComments.Text = XMLstring
End Sub
Public Function GetData() As DataTable
Dim dt As New DataTable
Dim adp As New SqlDataAdapter("usp_TR_Data", conn)
adp.SelectCommand.CommandType = CommandType.StoredProcedure
adp.SelectCommand.CommandTimeout = 150
With adp.SelectCommand.Parameters
.Clear()
.Add("@Action", SqlDbType.NVarChar).Value = "CONVERT-XML"
.Add("@SONo", SqlDbType.NVarChar).Value = Me.txtSONo.Text
End With
adp.Fill(dt)
Return dt
End Function
SQL Query
Select
[sname],[saddress1],[saddress2],[scity],[spostcode],[sstate],
[dairport],[scountry], [detailOfContent],[weight],[productPackages],
[dimensionX],[dimensionY],[dimensionZ],[chargeableRate],[rname],[rphone],
[raddress1],[raddress2],[rpostcode],[rcity],[rstate],[rairport],[rcountry],
[rremark],[rvia],[serviceModeId],[agentId],[trackingno]
From TR_Data
where SONo=@sono
[/INST]The error message "Cannot serialize the DataTable. DataTable name is not set" is saying that the TableName property of the DataTable object is not set. Please try to set the TableName property of the DataTable object before calling the WriteXml method. Something like:
dt.TableName = "YourTableName"
or by adding the table name on the function as an argument, like:</s> |
<s>[INST]SQL Redundant server
Hi
My SQL server is Microsoft SQL Server 2019 Standard.
My goal is to mirror the database on a backup server and to archive the database as well.
Is it necessary to upgrade it to SQL Enterprise? Where can I find instructions on how to do this?
Regards
Syed Haris Ahmed[/INST]You will have more options with Enterprise Edition, but you can achieve this on Standard Edition as well.
There are four options:
1. Log shipping. You apply the transaction log from the main server regularly. You can have read-only access to the mirror, but users will be kicked out every time logs are applied. Failing over to the mirror is a manual process. Since logs are only applied like every 15 minutes, there can be some data loss.
2. Transactional replication. Again, the secondary is readable, and this time without interruptions. Replication requires some work to setup, monitor and manage. Failover is manual. Here, too, you can get data loss in case of a failover.
3. Basic Availability Group. Logs are shipped constantly. Secondary is not readable(*). With synchronous mode failover can be automatic and without data loss. While AGs are less complex than replication, they still need care and monitoring.
4. Old style Database Mirroring. This is deprecated, use Basic Availability Groups instead.
(*) Readable secondaries require Enterprise Edition.</s> |
<s>[INST]I have two instances: payroll and PP (Production planning); currently, I have an employee(Demographic) table in both cases, and now data is loaded in both instances. I want to remove the employee table from PP and utilize the table from the payroll.
Hi,
I have two instances: payroll and PP (Production planning); currently, I have an employee(Demographic) table in both cases, and now data is loaded in both instances.
I want to remove the employee table from PP and utilize the table from the payroll.
1)
I decided to create the view in PP from SOARS using a linked server, which will slow the read options. Can I implement an external table using a polybase(Getexternal) data?
2\) Move the Payroll and the PP databases in one instance so that If I create a view employee in PP for the Payroll table employee, it will also allow me to read and write.
3\) If Azure or AWS support built-in functionality to share tables across two databases, that is also fine.
If somebody has already implemented or has an efficient way, please advise.
[/INST]I decided to create the view in PP from SOARS using a linked server, which will slow the read options. Can I implement an external table using a polybase(Getexternal) data?
Which version of SQL Server are you on? On SQL 2019, you can set up the table as an external table rather than using a linked server. This has some advantages, not the least with regards to security. However, external tables are read-only, so if you need to update the remote table, the linked server is a better alternative.
When it comes to speed, there is on reason to hope that the external table is faster. But since a lot depends on the query plan, and you could get a different plan with the external table, you could see major differences - in either direction. But generally, I think the overhead for Polybase is higher, since there are more services involved. This matters particularly, if you are running many short queries.
> 2\) Move the Payroll and the PP databases in one instance so that If I create a view employee in PP for the Payroll table employee, it will also allow me to read and write.
That is definitely a better option. You gain both in manageability and in speed. And what you lose? I don't know, but maybe there was a reason you set up two instances originally.
> 3\) If Azure or AWS support built-in functionality to share tables across two databases, that is also fine.
I don't know about AWS, but on Azure SQL Databases, you can set up external tables, but this is different from Polybase. I don't know if they are read-write, but I believe they are a more realistic option than external tables in Polybase.</s> |
<s>[INST]Sql Server db_ddladmin
Good afternoon.
I usually use the role db_ddladmin for my users of database, but i need to know, if i can to apply this role for one user in only one table. Does this is possible?
Thanks,
Marcos Aurelio G Guarnier[/INST]It is not possible to apply the db_ddladmin role to a user for a specific table. The db_ddladmin role grants the user permissions to perform all data definition language (DDL) operations in a database. This includes the ability to create, alter, and drop tables, as well as other database objects.
If you want to restrict a user's permissions to a specific table, you can do so by creating a user-defined database role and granting the appropriate permissions to that role for the specific table. Then, you can add the user to the user-defined role. This will allow the user to perform only the actions that have been granted to the role for the specified table.
For example, to create a role that has SELECT, INSERT, UPDATE, and DELETE permissions on a table called mytable, you can use the following T-SQL code:
CREATE ROLE myrole;
GRANT SELECT, INSERT, UPDATE, DELETE ON mytable TO myrole;
Then, to add a user myuser to the myrole role, you can use the following T-SQL code:
EXEC sp_addrolemember 'myrole', 'myuser';
This will allow the user myuser to perform SELECT, INSERT, UPDATE, and DELETE operations on the mytable table, but will not allow them to perform any other DDL operations in the database.
If this answer is helpful, please click ^ to vote. )</s> |
<s>[INST]What is the service name for SQL Server when installed by Visual Studio
I've installed the SQL Server modules with Visual Studio 2019. There are no services listed in "services" corresponding to SQL, MSSQL, Localdb, SQLExpress, or anything containing the letters "SQL". I've tried net stop with mssqlserver, sqlexpress, localdb, mssqllocaldb, and ProjectsV13, and each throws an error because the service name doesn't exist. "Select @@Servicename" returns "LOCALDB#6A3BFD14", which also doesn't appear in the Services list and results in a "service name doesn't exist" error when I try to name it using net stop. The SQL Server instance names are (localdb)\ProjectsV13 and (localdb)\MSSQLlocalDB.
I want to start and stop the sql service manually but I can't find the service name. Yes, SQL server is running, I can connect to it with VS and SSMS. To reiterate, SQL was selected as a module when installing Visual Studio. It wasn't installed separately using full SQL or express installations.
Thank you.[/INST]Localdb does not run as a service, but runs in your user space. You control your localdb instances with the `sqllocaldb` utility. Which I would expect to be in your path if you have opened a VS command prompt. `sqllocaldb -?` gives you information on how to run it.</s> |
<s>[INST]Relationship between two tables. questions..
Hi..
I have a real world question here. I am designing a small database that is used for a diner.
The diner has lunch specials. Only though, from Monday thru Friday. Not saturday and Sunday.
They of course also have a menu. I have two tables.
tblMenuItems
\-------------------
menuID
name
description
price
image (might end up on web and they want a pic to be displayed.
dateAdded
vendor
notes
tblLunchSpecials.
\--------------------
specialID
name
description
price
image (Again, may end up on web)
dayOfWeek (What day is the special for this item, ie, monday, tuesday, etc.)
vendor
notes
Ok.. A special can be a menu item. Is a menu item, but only for monday thru friday and is only a lunch item. Regular non special menu items can be breakfast or lunch as this is all the meals they serve.
Of course a menu item can be a special. But, not many.. Just 5 menu items are specials.
So, do I put all this in one table. It's only like 35 items. I could, but I'd like to know what you're really supposed to do as far as normalization goes.
Is this a many to many realtionship since both a menu item and a special can belong to each other ? Therefore would I need a linking or junction table?
There are other tables, but not related to the menu in this database and so I didn't include them..
Thanks
Tim[/INST]I was also going to suggest to keep just one table for menuitems and not have a separate specials table.</s> |
<s>[INST]Problems installing SQL Server 2014
I plan to install SQL Server 2014 on my home PC. Is there anything I need to
know to avoid install errors? This is a simple install on a standalone PC, no networking,
no fancy stuff. Just me and my box!
I've tried to install before, but I would usually encounter some install errors. This is because
I don't know enough about making parameter choices, what features to install or avoid, etc.
If I picked all features, some errors would always show up (can't install SSRS Reporting Services,
things like that.)
I thought a default install would go cleanly and easily. I know my home PC is a brand new one,
but still... I have lots of space on an M.2 NVMe, and at least 8 gigs DDR4 memory.
Any tips? Or is there a check list out there somewhere for installing a typical standalone setup?
I'll take notes on specific error messages next time. I just thought it would go smoothly, and it
didn't.
[/INST]The SQL Server 2014 is very old version, and out of support.
Microsoft released after that the following versions:
- 2016
- 2017
- 2019
- 2022
It is better to install SQL Server 2019 or even 2022, Developer Edition.
This way you will get all the latest functionality.
If needed, it is very easy to switch to any of the previous versions via **compatibility mode** setting.</s> |
<s>[INST]Hi,
I have an issue trying to bulk insert a file into my database.
I am getting the following error.
> Bulk load data conversion error (truncation) for row 2
Code is
> BULK INSERT Palletinfo
FROM 'c:\test\DHL 250121.csv'
WITH (FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR='\n'
);
**Example data**
id,Parcel_ID,Pallet_ID
,459431111756,100001
,459431111734,100001
,459431111740,100001
,459431111790,100001
,459431111762,100001
The column its inserting it into is nvchar
The document was originally an libre .ods file which I opened in Excel and saved as a CSV file after converting that field to a number due to it length.
I then opened it up in Notepad++ to check the data.
Any idea what is happening?
[/INST]Field was set to char 10 when string was 20 character.. changed it and it works</s> |
<s>[INST]Hi,
We have SQL Sentry installed for our SQL server 2014.
Today I saw a query in Blocking tab , that was block another query for short time:
"insert into dbo.test select * from dbo.test option (maxdop 1)" executed by sqlserveragent --This query was block some other
I could not get it as we do not run such queries manually or in any of the job.
We have a loging database, in which we log all running queries after a specifice given period in whole day. I looked into those logs & found that at same time index rebuild was in process on table dbo.test.
Does index rebuild executes such queries in backend working.
Regards,
Zahid[/INST]With help of Profiler, I can confirm that ALTER INDEX REBUILD indeed runs such a statement.
The statement may seem silly, but keep in mind that this is actually what SQL Server is doing: it copies the table (or the index) from one place to another.</s> |
<s>[INST]
hi experts, kindly plz suggest any tip:
I have replication from server 1 to server 2 from Database A
I have 20 tables for database A publication1 that runs fine
I have a separate table for the same database A publication2 with 23 million rows 52 columns
Publication2 snapshot ran fine took 10 minutes,distribution agent said no replicated transactions all good
and all of a sudden 4:56am I see distribution agent " delivering replicated transaction" and on subscriber is UPDATE of Distributor job taking ever
i don't see any jobs ran from 4 am-5am on the publisher ..
9am i tried to reinitialize with a new snapshot which caused heavy blocking on subscribers and almost took our system down.
i created the same snapshot the next day and now i have the same issue
"distribution agent " delivering replicated transaction" and on subscriber is UPDATE of Distributor job taking ever "
what i think is when there are updates happening on the table, log reader agent tries to insert to distribution db , distribution agent job try to read and update and same time distribution cleanup job tries to delete distribution agent ( msreplcommands, msrepltransactions table) and this is causing the issue
i don't see any blocking in Distribution db( note: publisher and distributor same SQL server 2016)
@immediatesync, all anonymous both =0
msdeleteublisher db changed from paglock to rowlock
shrink publisher A db to reduce VLF
nothing helped and i am thinking to stop the distribution agent clanup job for now, try to snapshot, re initialise and if all looks good, try to run the distribution cleanup non peak hours.
kindly please provide some tips
[/INST]i tried every suggestion which i got online, but nothing worked
The only fix was to recreate the snapshot every morning 7 am which is only for 1 table which is taking 3 mins
as at 6 am everyday bulk insert is happening on the publisher table, which is taking ever to deliver commands to the subscriber
subscriber always say UPDATE which never complete.
i have immediatesync=1, allow allowanonymous=1
invalidate the snapshot
run the snapshot,
the distribution will get the latest snapshot and deliver -all good</s> |
<s>[INST]Hi All,
Is there a way to tell at what level the index pages are fragmented ? is it leaf level or intermediate levels of the index is fragmented? just a side note, does sys.dm_db_index_physical_stats () show us leaf level fragmentation or does it shows intermediate level fragementation as well? if so, what are the output columns from sys.dm_db_index_physical_stats I can check?
Thanks,
'Sam
[/INST]sys.dm_db_index_physical_stats, gives you fragmentation on intermediate levels. It's the same columns for the leaf level. The level column will tell you which level the values are for.
Then again, I don't think the logical fragmentation of the intermediate levels are that interesting. The physical fragmentation, which you only get if you use DETAILED, is of some interest. Then again, if it's rarely low on the data pages and high on the intermediate levels.</s> |
<s>[INST]Hi,
I have a 2 node WSFC and I have synchronous AG with automatic failover.
My log file keeps on growing despite frequent successful log backups and dbcc sqlperf('logspace') shows 99.9% of space is used and the log is not getting truncated.
There are no long running open transactions transactions in my primary and we use secondary only to offload backup workload.
log*_ reuse_ wait _ desc* shows AVAILABILITY_REPLICA.My secondary replica is fully synchronized and log_send_queue and redo_log_queue size are normal.
I can only see a full backup in progress in my secondary which is running for more than 2 days.
Does a long running active full backup in secondary replica does not allow truncation of logs because sql engine needs the log information from the start of the full backup operation for successful completion of a consistent backup
[/INST]I'll be more than glad to help you out.
First I would recommend to troubleshoot why your full backup is running that long! If your database is that big then you should optimize the backup command with different options to speed up the process. If your database size is not that big... you might have a slow storage or having other problems causing the backup process not to finish.
From my understanding, after a successful log backup (after the full) everything should work as expected...
I hope my answer is helpful to you,
Your</s> |
<s>[INST]Below is data
I want ,when PID of #tbl*BalPacM exists in #Probale ,then it should not be sum where Pstatus of #tbl_BalPacM <>2.*
Below query i tried ,but it is not giving me expected output
```sql
Create table #Probale (Prdno int,prdqty int,PID int,orderno int)
Create table #tbl_BalPacM(PID int,E_Date date,PStatus int,orderno int)
Insert #Probale values(1001,1,111,13)
Insert #Probale values(1002,1,111,13)
Insert #Probale values(1003,1,NULL,13)
Insert #Probale values(1004,1,NULL,13)
Insert #tbl_BalPacM values (111,'2023-02-20',2,13)
select sum(prdqty)qty from #Probale P left join #tbl_BalPacM M on P.PID=M.PID and M.PStatus<>2
where P.OrderNo=13
```
Expected Output=2
[/INST]](/users/na/?userid=04a7df5d-3194-4af9-a2ed-9f558358cca8)
I modified your query a bit, you can try it.
```sql
select sum(prdqty)qty from #Probale P left join #tbl_BalPacM M on P.PID=M.PID
where P.OrderNo=13 and (M.PStatus <> 2 or M.PStatus is null);
```
You can put the M.PStatus<>2 condition after where. Since M.PStatus<>2 can't filter out null values, I added an OR or M.PStatus is null, and now this query can output 2.</s> |
<s>[INST]I am using a SQL database project and I have the configurations saved in JSON format.
It is currently stored in a string which is not so good for maintenance, like this:
```tsql
CREATE FUNCTION mpp.GetNotificationWorkflow()
RETURNS NVARCHAR(MAX)
AS
BEGIN
--1
DECLARE @Json NVARCHAR(MAX) =
'[
{
"StepType": "Initiate",
"Id": "Initiate",
"Name": "Initiate",
"OnInitiate": "OrgUnit planners"
},
{
"StepType": "ApproveOrReject",
"Id": "OrgUnit planners",
"Name": "OrgUnit planners",
"Repository": {
"Name": "AssignmentRequestNotificationPlanners",
"OrgUnitTypeId": 0
},
"OnApprove": "Complete",
"OnReject": "Complete"
},
{
"StepType": "Complete",
"Id": "Complete",
"Name": "Complete"
}
]';
RETURN @Json;
END;
GO
```
I would like to keep this configuration in a separate .json file for convenience. Is it possible?
[/INST]To load it from file:
```SQL
create function mpp.GetNotificationWorkflow()
returns nvarchar(max)
as
begin
declare @json nvarchar(max)
select @json = BulkColumn from openrowset (bulk 'C:\SomeFolder\MyFile.json', single_clob) t
return @json
end
```
The file must be placed to some accessible folder (on SQL server, for example).
Maybe it has sense to keep it (to some optimised table), avoiding multiple disk operations.
Perhaps there are other convenient solutions for database projects.</s> |
<s>[INST]I am trying to use the NOT IN function to return an output with certain fields stripped out.
For example I am trying return a table without the value 'Recruiting' or 'Natural' contained in the department field.
I tried the following:
```
SELECT
*
FROM dbo.investmgmt
WHERE investmgmt.department NOT IN ('%Natural%')
```
I have created some sample data:
```
CREATE TABLE investmgmt (
department varchar(250),
company_name varchar(100))
INSERT investmgmt VALUES
('Strategy and Investment at ByteDance','ByteDance'),
('Investment management','Devon Equity Management Limited'),
('Senior Investment and Asset Manager','The Instant Group'),
('Director - Investment Banking & Law at Pinpoint Partners','Pinpoint Partners'),
('Recruiting talented Developers/Engineers into the Investment Banking and Investment Management Industries','Cornwallis Elt'),
('Investment Manager at Beringea','Beringea'),
('Investment Management - Natural Capital and Sustainable Farmland','Climate Asset Management'),
('Principal, Fund Manager','Columbus Capital Ltd'),
('CEO | ESG Investment Partners | Green Economy | ESG Procurement | Asset Management | M&A |','IZECORP INVESTMENTS'),
('Investment Banking Analyst at BNP Paribas','Deloitte'),
('Property Investment | Property Development | Finance','Nova Financial Group')
SELECT * FROM investmgmt
```
Any thoughts?
[/INST]NOT IN is not a function. Let's start from beginning. If you say:
sql
SELECT * FROM tbl WHERE col IN (1, 2, 3)
This is a syntactic shortcut for
sql
SELECT * FROM tbl WHERE col = 1 OR col = 2 OR col 3
You can easily see this with help of an error message.
sql
CREATE TABLE #t (a int NOT NULL)
SELECT a FROM #t WHERE b IN (1, 2, 3)
You get these errors:
> Msg 207, Level 16, State 1, Line 26
> Invalid column name 'b'.
> Msg 207, Level 16, State 1, Line 26
> Invalid column name 'b'.
> Msg 207, Level 16, State 1, Line 26
> Invalid column name 'b'.
You get there error messages, because before the binder comes around to look for the columns, the parser has already rewritten the IN to a list of OR conditions.
Now that you know what IN means, you also understand what NOT IN means. That is:
sql
SELECT * FROM tbl WHERE col NOT IN (1, 2, 3)
is the same as
SELECT * FROM tbl WHERE NOT (col = 1 OR col = 2 OR col = 3)
Or, with some boolean algebra:
sql
SELECT * FROM tbl WHERE col <> 1 AND col <> 2 AND col <> 3
In your example you had `%Natural%`. I assume that you had some wildcard thingie in mind. If you want to use wildcards, you need to use the LIKE operator. But for the LIKE operator there is no syntactic shortcut, but you need to write
SELECT * FROM tbl WHERE col NOT LIKE '%this%' AND col NOT LIKE '%that%'</s> |
<s>[INST]Hi guys,
Can I add a SQL server under the central management server which is not part of the domain? So is for example a workgroup SQL server.
Hope someone knows the answer.
kind regards
Marco[/INST]](/users/na/?userid=ff11126f-2e38-4140-9d9b-33f46c050d1a),
In the first link I post, we can read this content:
*There is one other disadvantage. All registered server connections in the CMS can only use Windows authentication. This means you can only add servers to your CMS that are in the same domain or a trusted domain. You will not be able to add standalone servers that are not in a domain. We generally see this in a DMZ scenario where the SQL Server hosts data for a public facing web server. Along those lines, we typically see that test and development environments are hosted in separate untrusted domains. You will not be able to add these servers either. In these scenarios, you will need a separate CMS in each untrusted domain.*
Because the machines in my environment are in the domain, I have no way to do the test.</s> |
<s>[INST]Hello Community,
I'm getting the following error
```
Incorrect syntax near the keyword 'FROM'.
```
When I execute the following query:
```
WITH cte AS ( SELECT accountid FROM STRING_SPLIT(ts_montaguoffice, ';') as ts_montaguofficeonly
FROM core.account ) SELECT accountid, ts_montaguofficeonly
FROM cte CROSS APPLY (SELECT value FROM STRING_SPLIT(ts_montaguofficeonly, ';')) as split
```
I know its something simple, but could someone let me know how to resolve this error?
Thanks
[/INST]This works for me:
```SQL
SELECT accountid, t.value as ts_montaguofficeonly
FROM core.account
cross apply ( select value from STRING_SPLIT(ts_montaguoffice, ';')) as t
```</s> |
<s>[INST]hi all,
I need to write a query that transforms a table like this:
Emp Id LastName FirstName DOB ....
123 Smith John 1980-12-28
456 Wilson Jack 1982-04-12
...
into
Emp ID Value
123 Smith
123 John
123 1980-12-28
...
456 Wilson
456 Jack
456 1982-04-12
Thanks,
elsvieta
[/INST]microsoft.com/en-us/users/na/?userid=74e3380d-64d7-4d1a-92c0-da7ecd25405a),
Please try the following solution.
tsql
-- DDL and sample data population, start
DECLARE @tbl TABLE (EmpID INT PRIMARY KEY, LastName VARCHAR(20), FirstName VARCHAR(20), DOB DATE);
INSERT @tbl (EmpID, LastName, FirstName, DOB) VALUES
(123, 'Smith ', 'John', '1980-12-28'),
(456, 'Wilson', 'Jack', '1982-04-12');
-- DDL and sample data population, end
SELECT t.EmpID, t1.col
FROM @tbl AS t
CROSS APPLY (VALUES
(LastName),
(FirstName),
(TRY_CAST(DOB AS CHAR(10)))
) AS t1(col);</s> |
<s>[INST]Hi i have transaction replications one publisher and one subscriber. I am looking to stop the replication for few days due to some business requirement(intention is to stop updates goes to subscriber site) . since I know there is retention period for subscribers 72 hours (default) to expire. since I dont want to rebuild it again after days which cross 72 hours , I should able to start the replication back normal no issues and start sync again
Distribution Db; I make sure have enough space on distribution Db to hold the data
If I stop just log reader, then will that sufficient ?
on publisher server :
Distribution clean up job run every 3 min. so its running as usual
Expired subscription clean up : every day 1am. so its running as usual
on Subscriber server:
REPL-Distribution job run continuously : so its running as usual
please advice my steps are correct (if any one knows)
[/INST]You just need to stop the distribution agent for the subscriber. Then it will not apply any changes to the subscriber. The default name is "servername-databasename-replicationname...".
You do not need to touch the distribution agent jobs. The cleanup jobs remove DELIVERED commands. Undelivered commands are never removed.
Note: This is going to cause your distribution database to grow, since it cannot deliver the commands, until you turn the agent back on.</s> |
<s>[INST]hi There
we have SQL server 2016 SP3 enterprise two node SQL servers alwayson enabled secondary site available as read_only to access read only data. new application has been developed to connect to readonly using group listener . note :both nodes on same subnets
Q1. What is the best method /improved drivers to connect readonly using read only routing Using System.Data.SqlClient or MSOLEDBSQL, OELDB or SQLNCLI
Q2: What would be the connection string for System.Data.SqlClient
data source=Listenenrname;database=DB;Integrated Security=SSPI;ApplicationIntent=ReadOnly;
many thanks[/INST]Which client API you use largely depends on what the client is written in. For a client written in .NET, you would use SqlClient. For a native application written in C++, you would use the most recent ODBC driver. You would only use an OLE DB provider, if you already have an application that is using OLE DB. In that case you should use MSOLEDBSQL19 which is the most recent OLE DB provider.
The connection string will be the same no matter the API, save for that keywords may vary. The above looks good, but give that there is some inconsistency with spacing, it is always good idea to look up a reference.</s> |
<s>[INST]I have made a small ecommerce website using python
The page displays a table and some buttons
Below the table is supposed to be a list of possible pages
For some reason my page is displaying the possible pages above the table.
The page seems to be displaying out of order for some reason.
The table does load in some sql server data so maybe that is why ?
The code definitely has the possible pages links last.[/INST]The problem was missing table end tag.</s> |
<s>[INST]Hello,
I am working on the following query -
SELECT DISTINCT [CM_TAN].[dbo].[v_FullCollectionMembership].[Name] AS Asset,
[CM_TAN].[dbo].[v_Collections].CollectionName AS Collection_Name
FROM [CM_TAN].[dbo].[v_FullCollectionMembership]LEFT JOIN [CM_TAN].[dbo].[v_Collections] ON [CM_TAN].[dbo].[v_FullCollectionMembership].CollectionID = [CM_TAN].[dbo].[v_Collections].CollectionID
Order By Asset DESC
I am getting this error -
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value 'SMS00001' to data type int.
I know why but I am not sure how to fix it. It is probably simple for someone with a better understanding of SQL then I have.[/INST]In the LEFT JOIN condition you need to make sure that both columns are nvarchar so you need to do
cast([v_FullCollectionMembership].CollectionID as nvarchar(30)) = cast([v_Collections].CollectionID as nvarchar(30))
The query will be slower with that, but should work.</s> |
<s>[INST]Server: Windows Server 2019
SSMS access for all users
Question: I was asked to install SQL Server Management Studio on the above server. All users on that server should have access to the SSMS. I logged in to that server, downloaded SSMS in C drive and installed it.
Do all the users have access to that SSMS or just me ? How do I make sure that everyone will have access to SSMS ?
Thank you.[/INST]If you used the default location (that is C:\Program Files (x86)\SQL Server Management Studio), it should be accessible for all users.</s> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.