text
stringlengths
209
10.7k
<s>[INST]MSSQL 2014 - maintenance task - what is the default fragmentation level ? Hi all, I really like to know what is the default fragmentation % level that SSMS 2014 takes when run a reorg or reindex maintenance task. In the latest SSMS release I can select the fragmentation % level to consider when I run a reorg index maintenance plan. In SSMS 2014 there is no option. So I really like to know what is the rule that SSMS apply when we run a reorg index maintenance task? what is the fragmentation % option that it applies? thank you for any help [/INST]what is the fragmentation % option that it applies? On older maintenance task there is no limit/check on the fragmentation ratio, the task simply rebuild/reorg all indexes; a reason why only less DBS uses maintenance tasks.</s>
<s>[INST]sql Datatype convert I am getting the following error. I know it datatype error, the thing is here is work early now it failed with this error. c# code long cdrid execute.sp(getcdrdetailsrange @cdrid = cdrid) SQL CODE sp getcdrdetailsrange(@cdrid int) ( select * from cdrdetails where cdrid>@cdrid; ) ERROR: Error converting data type bigint to int. TYPE: System.Data.SqlClient.SqlException why it works so many years and now erroring out [/INST]Probably after the years the values of *cdrid* became greater than 2,147,483,647. If the column is *bigint*, then change *int* to *bigint* in your *getcdrdetailsrange* and other SQL scripts. Also make sure that the corresponding C# variables are *long*.</s>
<s>[INST]How to do Query in Sql Server Hi... I have a problem .... I'm trying to execute This Querry but give me an error insert into GenStoTable(ProductID,StID,Quantity,LowQ)(select (select id from ProductTable),max(ID),0,0 from StrNamTable) I'm trying to use insert into with select from 2 tables .... please help me ... and thank's alot [/INST]Try removing "( )": insert into GenStoTable(ProductID, StID, Quantity, LowQ) select (select id from ProductTable), max(ID), 0, 0 from StrNamTable It assumes that *ProductTable* has a single row, otherwise it cannot work. Give details if you need something different.</s>
<s>[INST]Case Statement - End with a Blank Value Hi, I have a Case Statement but to close it off, I have else ' ' end as 'Variable_Name' This then still outputs a 0 but I want it to be blank. Any idea how I can do this please?[/INST]Try casting the expressions that appear before *else*, for example:  *... then cast(Co_Numeric as varchar(max)) else ' ' end as 'Variable_Name'* Sometimes you can use *NULL* instead of ' '.</s>
<s>[INST]Conversion failed Hi, I have ran my code and have an error come up that I really don't know how to resolve. Msg 245, Level 16, State 1, Line 40 Conversion failed when converting the nvarchar value '318.00' to data type int. This is my code: select distinct substring(a.cust_no,5,6) as job_number, a.mort_yearmonth as comp_date, a.gross_profit as gp, substring(b.supp_Code,3,7) as supp_id from [TWX].[dbo].[CUST_JOBS] as a left join [TWX].[dbo].[CUST_REF] as b on substring(a.cust_no,5,6) = b.cust_no_only Just to note - a.cust_no is usually set up as 1/000123456.123 where as b.cust_no_only is set up as 123456 I have tried to wrap a substring around a.cust_no so it can directly match to b.cust_no_only and I suspect that this is the problem here. Any idea how to resolve this please? [/INST]If *b.cust_no_only* ('123456') is expected to be a part of *a.cust_no* ('1/000123456.123'), then maybe try something like this: select . . . on substring(a.cust_no, charindex('/', a.cust_no) + 1, charindex('.', a.cust_no) - charindex('/', a.cust_no) - 1) = b.cust_no_only Or redesign the tables to avoid such string operations.</s>
<s>[INST]Basic permissions questions about read-only I need to give read-only access to a set of databases to a SQL login -- either an AD group or SQL user. What is the practical difference or benefit of assigning SELECT ALL USER SECURABLES to the login vs just mapping the user to the databases and assigning db_datareader database role? Thanks.[/INST]The difference it that the first option does not meet your requirements, while the second does. That is, even if you grant a login SELECT ALL USER SECURABLES, you still need to map that login to a database user in each database you want the user to be able to access. Once you have done this, you don't need to add the user to db_datareader, though. I would recommend that you go with db_datareader. The main purpose of this permission is actually to DENY users who have CONTROL SERVER permission (which permits them to access any database). That is, such a user can change code, tables, add users etc in a database, but can't see any user data.</s>
<s>[INST]MS SQL Server auto growth What is the trigger to initiate a database auto growth based on the defined auto growth settings? When does auto growth happen on a database?[/INST]What is the trigger to initiate a database auto growth based on the defined auto growth settings? When does auto growth happen on a database? These are essentially the same question. The answer is that the database will autogrow when the database storage management is not able to quickly find free space to allocate to the object. This could be for things such as indexes and heaps, text trees, etc., but SQL Server does not try to be exhaustive for space reuse, thus there will always be a little be of unused space depending on the pattern of the workload over the given time period.</s>
<s>[INST]Upgrading SQL 2012 to 2017 Hello. i have windows server 2012 r2 and it is running SQL server 2012 Enterprise. I want to upgrade SQL 2012 to 2017/2016. Do i need to purchase any license for this upgrade and can i use the same server for upgrade to i have to prepare new server for this upgrade. thanks.[/INST]SQL Server licenses are bound to the version. If you want to upgrade to a new version, then you have to purchase new licenses. You can perform an in-place migration, then everything stays the same, only SQL Server is a new version.</s>
<s>[INST]Question on backing up clustered instance Hello, It's rather strange but I failed to find information about best practices on backing up clustered SQL Server instances in my MS textbooks (official curriculums) as well as on the technet - would anyone please share a link to such documents should they exist? I'm asking that question because I can't seem to make my clustered SQL Server instance to backup to another shared drive (another LUN) which I've already added to the SQL Server's resource group - it can only "see" the LUN (disk) which had been selected during setup... Thank you in advance, Michael[/INST]It doesn't matter if it's a cluster or stand-alone server, SQL Server backup works always the same way > backup to another shared drive If you mean a NAS share, the you can not "see" it in backup wizard. You have to use plain T-SQL backup command and address the share by UNC path.</s>
<s>[INST]Alwayson Setup Hi Experts, Would you be aware of some application/database restrictions on a general basis wherein they would not be compatible with AlwaysOn AG , maybe some suggestions by MS If can please guide [/INST]The AlwaysOn AG feature is transparent for the clients, they are not aware of. But if you have doubt's, then ask the software vendor, he should know it best.</s>
<s>[INST]SQL server memory issue I am using SQL Server 2016 SE. When I used Update statistics Maintenance plan , the SQL server memory go on increasing & it will never come down. Maintenance plan successfully completed but it not come down memory . Can anybody suggest how to release memory from sql server. Thanks in advance.[/INST]You don't want to release memory from SQL Server, period. SQL Server is designed to grab as much memory as it can. It reads the data into the buffer cache, as reading from cache is faster than reading from disk. Once it has read data into cache, what would be the point with throwing that memory away, as long as it is not needed for anything else? If there other processes running on the machine and there is memory pressure, SQL Server will yield memory, don't worry. Although, sometimes SQL Server may not yield fast enough, and if other processes are suffering, you can set "max server memory" to limit how much memory SQL Server can consume. For instance, if you are running SQL Server on your laptop, where there are lot of other things going, you may want to run EXEC sp_configure 'max server memory', 4000 RECONFIGURE to cap SQL Server at 4GB of memory. But don't do this on a production server which is dedicated to run SQL Server.</s>
<s>[INST]how to make these two statment on one statment for update? I work on sql server 2012 i need to make update statement on one statment instead of using two statment select p.chemicalid,count(p.chemicalid) as CountChemicals into #countchemicalprofiles from parts.chemicalprofiles p with(nolock) inner join #TempPC t on t.chemicalid=p.chemicalid group by p.chemicalid UPDATE t SET t.[status] = 'Count chemical on profile not equal Master' FROM #TempPC t INNER JOIN #countchemicalprofiles cm ON cm.chemicalid = t.chemicalid AND cast(cm.CountChemicals as int)<>t.RowsCount WHERE t.[status] IS NULL so how to do that please ? [/INST]Try something like this: ; with countchemicalprofiles as ( select p.chemicalid,count(p.chemicalid) as CountChemicals from parts.chemicalprofiles p with(nolock) inner join #TempPC t on t.chemicalid=p.chemicalid group by p.chemicalid ) UPDATE t SET t.[status] = 'Count chemical on profile not equal Master' FROM #TempPC t INNER JOIN countchemicalprofiles cm ON cm.chemicalid = t.chemicalid AND cast(cm.CountChemicals as int)<>t.RowsCount WHERE t.[status] IS NULL</s>
<s>[INST]Add rows based on Start and End Date Hi, I have the following table within my output Cust_No Start_Date End_Date Comp_Val Monthly_Val 123 2021-03-18 2022-03-17 1100 91.66 As you can see, the months between start_date and end_date for this example, is 12 months. What I would like to see is a row for each Year_Month between Start_Date and End_Date with a new variable added **Example** Cust_No Start_Date End_Date Comp_Val Monthly_Val Year_Month 123 2021-03-18 2022-03-17 1100 91.66 2021-03 123 2021-03-18 2022-03-17 1100 91.66 2021-04 123 2021-03-18 2022-03-17 1100 91.66 2021-05 123 2021-03-18 2022-03-17 1100 91.66 2021-06 123 2021-03-18 2022-03-17 1100 91.66 2021-07 123 2021-03-18 2022-03-17 1100 91.66 2021-08 123 2021-03-18 2022-03-17 1100 91.66 2021-09 123 2021-03-18 2022-03-17 1100 91.66 2021-10 123 2021-03-18 2022-03-17 1100 91.66 2021-11 123 2021-03-18 2022-03-17 1100 91.66 2021-12 123 2021-03-18 2022-03-17 1100 91.66 2022-01 123 2021-03-18 2022-03-17 1100 91.66 2022-02 123 2021-03-18 2022-03-17 1100 91.66 2022-03 Any idea how this could be done please? [/INST]Check a solution that is based on recursion: ; with Q as ( select Cust_No, Start_Date, End_Date, Comp_Val, Monthly_Val, eomonth(Start_Date) as d from MyTable union all select Cust_No, Start_Date, End_Date, Comp_Val, Monthly_Val, dateadd( month, 1, d) as d from Q where dateadd( month, 1, d) <= eomonth(End_Date) ) select Cust_No, Start_Date, End_Date, Comp_Val, Monthly_Val, convert( char(7), d, 23) as Year_Month from Q order by Cust_No, d</s>
<s>[INST]Increasing SQL Worker Threads and Server Performance Hello, we are frequently having to increase the Max SQL Worker Thread counts on our SQL Server or else our backups start to fail because the SQL Server Writer gets messed up. What is the long term effect of increasing the Worker Thread count? Does it just impact the CPU performance? Seems that the CPU, Memory and Network utilization is just fine. Want to make sure that there isn't anything else that I should be looking for. Thank you![/INST]we are frequently having to increase the Max SQL Worker Thread counts on our SQL Server or else our backups start to fail because the SQL Server Writer gets messed up. My guess here, based on this, is that you have a server with a small number of cores but a large number of databases which would make it undersized but we're lite on details here. If you don't have a problem with anything else and just VSS backups, then have the VSS software backup only a few databases at a time. Since you didn't give me really any data or information to work with, that's the best I can do. >What is the long term effect of increasing the Worker Thread count? Bad performance. SQL Server will only create new threads if it has to and when the threads go idle they will eventually be destroyed. Having a high ratio of threads/core means more context switching and less time actually doing work. It can also put more strain on the windows scheduler and can lead to other issues like non-yielding scheduler dumps and the common, "SQL is frozen" or "SQL is slow" generic issues. I'm not saying it *will* happen, just those are the most common. Basically there is no reason to really touch this value. I tend to find places here and there that change them and when I ask why, it's always to "fix" some other underlying terrible issue. In this instance, I think changing the backup software to not do all databases at once is the best course of action instead of changing this value.</s>
<s>[INST]Running a remote .cmd / .bat from SSIS Process Task Hi there, I am trying to run this from this task with these two properties: **Executable:** \\servername\c$\Program Files (x86)\Common Files\xxx\Batch\Monthly_Total.cmd **Working directory:**\\servername\c$\Program Files (x86)\Common Files\xxx\Batch\ But it is failing and I getting this message: 'path..... CMD.EXE was started with the above path as the current directoy. UNC paths are not supported. Defaulting to Windows directory The user has fully permissions on the remote virtual machine, it is Local Admin Any thoughts? I remember have used this task in the past successfully against a remote server Thanks in advance,[/INST]You need to create a network file share for the UNC to be functional. Along the following:</s>
<s>[INST]How to consume data returned from recurcieve CTE in SQL I have a table in sql db that looks like this: Matrix Table Id Child Parent Level ----+-----------+-----------+---------- 1 Q-00001 Q-00000 NULL 2 Q-00002 Q-00001 NULL 3 Q-00003 Q-00001 NULL 4 Q-00004 Q-00002 NULL 5 Q-00005 Q-00002 NULL 6 Q-00006 Q-00003 NULL 7 Q-00007 Q-00003 NULL 8 Q-00008 Q-00004 NULL 9 Q-00009 Q-00005 NULL 10 Q-00010 Q-00006 NULL 11 Q-00011 Q-00007 NULL 12 Q-00012 Q-00005 NULL 13 Q-00013 Q-00004 NULL and the out come looks like this: Expected Result: Child Parent Level -----------+----------+--------- Q-00002 Q-00001 1 Q-00003 Q-00001 1 Q-00004 Q-00001 2 Q-00005 Q-00001 2 Q-00006 Q-00001 2 Q-00007 Q-00001 2 Q-00008 Q-00001 3 Q-00009 Q-00001 3 Q-00010 Q-00001 3 Q-00011 Q-00001 3 Q-00012 Q-00001 3 Q-00013 Q-00001 3 the sql query is as below: ;WITH downlines(Child,Parent,Level) AS ( SELECT Child, Parent, 1 FROM \[Matrix2\] WHERE Parent = 'Q-00001' UNION ALL SELECT m.Child, d.Parent, d.level +1 FROM downlines d INNER JOIN Matrix2 m ON d.Child = m.Parent ) SELECT \* FROM downlines ORDER BY Child,Parent, Level ; My question is how do I modify the above query to be able to do further task when the CTE table is returned. I want to do a task like, SELECT COUNT(Level) FROM (CTE table) WHERE Level = 2 [/INST]Simply the same way as in your example query => ;WITH downlines(Child,Parent,Level) AS ( SELECT Child, Parent, 1 FROM [Matrix2] WHERE Parent = 'Q-00001' UNION ALL SELECT m.Child, d.Parent, d.level +1 FROM downlines d INNER JOIN Matrix2 m ON d.Child = m.Parent ) SELECT COUNT(Level) FROM downlines WHERE Level = 2</s>
<s>[INST]Updating SQL Server with Windows Update I'm using SQL Server 2017 Standard. In the wizard window when installing it, when "Include SQL Server product updates" was set to ON and installed, the GDR update was installed by Windows Update. This setting does not install CU updates. The CU update that was manually downloaded from the Microsoft Update Catalog was able to be installed without any problems. Can I change this "Include SQL Server product updates" setting after the installation is complete? What I mean is a change, such as switching the update to be installed between GDR and CU, or turning automatic updates on/off with Windows Update. (I'm inexperienced with SQL Server updates and it's hard to understand by reading Microsoft documentation, so I might be asking strange questions...) ================================================== It seems that only GDR is downloaded in Windows Update. I'm going to use Windows Update on a DB server that uses GDR updates and manually download them from the Microsoft Update Catalog for DB servers that use CU updates. I would like to continue to ask questions about how to turn the "Include SQL Server product updates" setting on/off after installation is complete.[/INST]I would like to continue to ask questions about how to turn the "Include SQL Server product updates" setting on/off after installation is complete. There is no longer need to turn off “Include SQL Server product updates” in the Product Updates page of installation wizard after the installation is complete. The "Include SQL Server product updates" in the "Product Updates" page of the installation wizard will not affect subsequent updates after installation. When “Include SQL Server product updates” is selected during installing the SQL Server, the latest available SQL Server product updates are displayed. If you don't want to include the updates during installation, clear the Include SQL Server product updates check box.</s>
<s>[INST]How to calculate Monthly aggregates from daily data we have detail daily data in a table about members., trying to finding how many new members (by considering ID1, ID2, ID3 columns values) monthly totals. so we want to find out when is the ID1, ID2, ID3 combination first exist and mark add count for monthly. CREATE TABLE #MYSRCHISTORY_members ( ID_1 VARCHAR(10), ID_2 int, ID_3 VARCHAR(10), Pay1 varchar(6), Pay2 varchar(6), Status varchar(10) FileDate ) --- SOME MORE detail INFO about data --- WE HAVE ABOUT 2 YEARS WORTH OF DAILY FEEDS DATA LOADED TO ONETABLE(MYSRCHISTORY_members) last column FileDate shows what day is the file, --- USUALLY EACH DAY FILE HAVE ABOUT 30K RECORDS, IN WHICH IT INCLUDES OLD RECORDS AS IS, NEW ENTRIES ADDED (by considering id1,id2,id3 combination) , FOR SOME MEMBERS IT MAY CHANGE OTHER COLUMN VALUES. --- WE FOUND MEMBER BASED ON THREE id FIELDS, IF ID_1,2,3 CHANGES THEN IT IS CONSIDER AS NEW MEMBER. --- HERE WOULD LIKE TO KNOW HOW MANY NEWMEMBERS WERE ADDED PER EACH MONTH (MONTHLY AGGREGATION) ---Inserts 5 records in that file, 3 old 2 new (in 2 one is just id change one is INSERT INTO #MYSRC VALUES ('3120', 250, '3241', '120.75','0.00','EN-25', '09/20/2021') -- exist same set (id1,2,3) in earlier data, so not a new member for Sep INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '09/20/2021') -- exist same set (id1,2,3) in earlier data, so not a new member for Sep INSERT INTO #MYSRC VALUES ('3122', 250, '3243', '20.75','0.00','EN-25', '09/20/2021') -- exist same set (id1,2,3) in earlier data, so not a new member for Sep INSERT INTO #MYSRC VALUES ('7120', 250, '3241', '120.75','0.00','EN-50', '09/03/2021') --New RECORDS because of ID1 change, INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '09/03/2021') ---Old RECORDS/member INSERT INTO #MYSRC VALUES ('1122', 250, '3243', '20.75','0.00','EN-25', '09/02/2021') --old record INSERT INTO #MYSRC VALUES ('1123', 252, '3244', null,null,'EN-25', '09/02/2021') --old record/member INSERT INTO #MYSRC VALUES ('1122', 27, '3243', '20.75','0.00','EN-25', '09/01/2021') --New Set of ID1,2,3 not exist in earlier data so count it as new member for SEP INSERT INTO #MYSRC VALUES ('1123', 252, '3244', null,null,'EN-25', '09/01/2021') --New Set of ID1,2,3 not exist in earlier data so count it as new member for SEP ---- August Data below - FileDate (last column) INSERT INTO #MYSRC VALUES ('3120', 250, '3241', '120.75','0.00','EN-25', '08/31/2021') -- exist same set (id1,2,3) in earlier data, so not a new member for Aug INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '08/31/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for Aug INSERT INTO #MYSRC VALUES ('3122', 250, '3243', '20.75','0.00','EN-25', '08/31/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for Aug INSERT INTO #MYSRC VALUES ('3120', 250, '777', '120.75','0.00','EN-25', '08/30/2021') --New Set of ID1,2,3 not exist in earlier data so count it as new member for Aug INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '08/30/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('3120', 250, '3241', '120.75','0.00','EN-25', '08/29/2021') -- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '08/29/2021') -- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('3122', 250, '3243', '20.75','0.00','EN-25', '08/29/2021') -- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('3120', 250, '888', '120.75','0.00','EN-25', '08/18/2021') ---same set (id1,2,3) not exist earlier, appeared first in Aug 2021. so count it INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '08/17/2021')--- exist same set (id1,2,3) in earlier data, so not a new member for Aug INSERT INTO #MYSRC VALUES ('1121', 37, '3242', null,'3.00','FU-25', '08/11/2021') --- New Set of ID1,2,3 not exist in earlier data so count it as new member for AUG INSERT INTO #MYSRC VALUES ('3122', 36, '100', '20.75','0.00','EN-25', '08/11/2021') ---New Set of ID1,2,3 not exist in earlier data so count it as new member for AUG ---- July Data below INSERT INTO #MYSRC VALUES ('3120', 250, '3241', '120.75','0.00','EN-25', '07/31/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '07/31/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('9122', 250, '3243', '20.75','0.00','EN-25', '07/31/2021') -- New Set of ID1,2,3 not exist in earlier data so count it as new member for July INSERT INTO #MYSRC VALUES ('3120', 250, '777', '120.75','0.00','EN-25', '07/20/2021') -- New Set of ID1,2,3 not exist in earlier data so count it as new member for July INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '07/20/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('3120', 250, '3241', '120.75','0.00','FU-25', '07/10/2021') -- New Set of ID1,2,3 not exist in earlier data so count it as new member for July INSERT INTO #MYSRC VALUES ('6121', 251, '3242', null,'3.00','FU-25', '07/10/2021') -- New Set of ID1,2,3 not exist in earlier data so count it as new member for July INSERT INTO #MYSRC VALUES ('3122', 250, '3243', '20.75','0.00','EN-25', '07/10/2021') -- New Set of ID1,2,3 not exist in earlier data so count it as new member for July INSERT INTO #MYSRC VALUES ('3120', 250, '888', '120.75','0.00','EN-25', '07/05/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('5121', 251, '3242', null,'3.00','FU-25', '07/05/2021')-- New Set of ID1,2,3 not exist in earlier data so count it as new member for July INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '07/01/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('4122', 250, '100', '20.75','0.00','EN-25', '07/01/2021') -- New Set of ID1,2,3 not exist in earlier data so count it as new member for July ---- Jun INSERT INTO #MYSRC VALUES ('3120', 250, '888', '120.75','0.00','EN-25', '06/05/2021') INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '06/05/2021') INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '06/01/2021') INSERT INTO #MYSRC VALUES ('3122', 250, '100', '20.75','0.00','EN-25', '06/01/2021') --- assume jun 2021 is Starting population Expected Output Date, NewMembersCount Jun-2021, 0 -- The oldest in the file table can make all 0's or simply just rows count July-2021, 7 -- 7 new members were added on July 2021 Aug-2021,4 -- 4 new members were added on July 2021 Sep-2021,3 -- 3 new members were added on July 2021 Thank you ASita[/INST]Based on Viorel's query, please refer below updated one and check whether it is helpful. ;with MY as ( select distinct month(FileDate) as m, year(FileDate) as y from #MYSRC ), F as ( select top(1) m as fm, y as fy from MY order by y, m ) select format(datefromparts(y, m, 1), 'MMM"-"yyyy') as [Date], case when m = fm and y = fy then 0 else (select count(*) from ( select id_1, id_2, id_3 from #MYSRC where month(FileDate) = m and year(FileDate) = y except select id_1, id_2, id_3 from #MYSRC where year(FileDate) < y or (year(FileDate) = y and month(FileDate) < m) ) d ) end as NewMembersCount , case when m = fm and y = fy then 0 else (select count(*) from ( select id_1, id_2, id_3 from #MYSRC where month(FileDate) = m and year(FileDate) = y and left(Status,2)='EN' except select id_1, id_2, id_3 from #MYSRC where year(FileDate) < y or (year(FileDate) = y and month(FileDate) < m ) ) d ) end as EUMembersCount , case when m = fm and y = fy then 0 else (select count(*) from ( select id_1, id_2, id_3 from #MYSRC where month(FileDate) = m and year(FileDate) = y and left(Status,2)='FU' except select id_1, id_2, id_3 from #MYSRC where year(FileDate) < y or (year(FileDate) = y and month(FileDate) < m ) ) d ) end as FUMembersCount from MY, F order by y, m Output: Date NewMembersCount EUMembersCount FUMembersCount Jun-2021 0 0 0 Jul-2021 7 5 2 Aug-2021 2 1 1 Sep-2021 4 4 0</s>
<s>[INST]Each GROUP BY expression must contain at least one column that is not an outer reference I have a query below that is returning the error above. Any help is greatly appreciated @ubid is passed in to the stored proc and its an int create table #process (processid int); insert into #process (processid) select id from TableB where filename like '%\%' + @reconID + '\' + convert(varchar,@ubid) + '\%' order by id asc insert into tableA(ubid, page, code, date, field) select @ubid, page, code, date, field FROM tableA WHERE processid in (select processid from #process) GROUP by @ubid, page, code, date, field ORDER by id asc [/INST]This script runs without error for me: DROP TABLE IF EXISTS TableB DROP TABLE IF EXISTS tableA DROP TABLE IF EXISTS #process go CREATE TABLE TableB(id int, filename sysname) CREATE TABLE tableA(id int, ubid int, page int, code int, date date, field int, processid int) go DECLARE @ubid int, @reconID varchar(12) create table #process (processid int); insert into #process (processid) select id from TableB where filename like '%\%' + @reconID + '\' + convert(varchar,@ubid) + '\%' order by id asc insert into tableA(ubid, page, code, date, field) select @ubid, page, code, date, field FROM tableA WHERE processid in (select processid from #process) --GROUP by @ubid, page, code, date, field ORDER by id asc I get the same error message as you, if I include the GROUP BY. The error message is due to the variable, which has no place in the GROUP BY clause. However, there is no point in the GROUP BY clause at all, since you are not aggregating on anything. And only removing the varible will give you a new error due to the ORDER BY clause. Which also is kind of pointless, since you are inserting the data into a table.</s>
<s>[INST]Configuration Option agent XPs changed from 0 to 1 Hi A few days ago, on the log erro of the SQL Server i had the next message: "[External]Configuration option 'Agent XPs' changed from 1 to 0. Run the RECONFIGURE statement to install. " The solution of the issue it´s not important, i need to know what produced this issue, could be an administrator or a program? . **I don´t have the windows event log because it´s recycled every day. Only the SQL log. Thanks[/INST]If you don't have auditing set up for these kind of things, it is about impossible to find out after the fact. It could be in the default trace if you are lucky, but I don't know this kind of event is captured there. And with five rollover files, the data in the default trace is not retained for a very long time.</s>
<s>[INST]Union Error Message Hi, I am trying to UNION 2 tables below to create the one table but when running it, I get the following error message: **Msg 8114, Level 16, State 5, Line 159 Error converting data type nvarchar to numeric.** I can only assume this has something to do with the SubStrings but can't work out how to resolve, any ideas please? Also, where would I place the INTO within this query please? select into [mort_db].[dbo].[final_mort] distinct a.invoice_number, substring(a.rep_co,5,6) as job, c.starting_date as start_date, substring(a.cust_code,3,7) as cust_id, b.fullname as userid, sum(c.mort_bal) over (partition by a.invoice_number , c.starting_date ) as mo_value, 'typ' as system from [mort_db].[dbo].[cust_db] as a left join [mort_db].[dbo].[mort_users] as b on a.[userid] = b.[userid] left join [mort_db].[dbo].[jp_fin] as c on a.invoice_number = c.invoice_number where a.draft = '0' and a.rep_co like '%98%' union select distinct finalinv as invoice_number, jobnumber as job, invoicedate as start_date, cust_no as cust_id, createby as userid, total_bal as mo_value, 'ssy' as system from [fa_db].[dbo].[inv] where af_status = 'test' [/INST]We recommend that you post CREATE TABLE statements for your tables together with INSERT statements with sample data, enough to illustrate all angles of the problem. We also need to see the expected result of the sample. > I can only assume this has something to do with the SubStrings but can't work out how to resolve You could have a try with below replacement. Replace below: substring(a.rep_co,5,6) as job With below: CASE WHEN Isnumeric(substring(a.rep_co,5,6)) = 1 THEN substring(a.rep_co,5,6) ELSE null END as job > where would I place the INTO within this query please? If the [mort_db].[dbo].[final_mort] table already exists, you could refer below as mentioned by other expert: Insert into [mort_db].[dbo].[final_mort] select * from ... union select * from ... Otherwise refer below: select * into [mort_db].[dbo].[final_mort] from (select * from ... union select * from ...) a</s>
<s>[INST]user migration Hi Expert, I have windows user(domainx/userA) with domain x who has account to 7 sql server instance  and i want to migrate this windows new server client with domainy/userA. Do i have to migrate or copy or move access all from 7 servers to new server or any one of the server is sufficient examples erver1,2,3,4,5,6,7- domainx/userANew Server-domainy/userAor how to take access all these seven server to new server?thanks,[/INST]If you're creating a new login (such as a new login for an account in DomainY) then you'll need to create it as a login on all the SQL Servers you'd like that login to have access. There is nothing stopping you from scripting out the login and associated users, then changing the name for the DomainY items, but again it'll all need to be created. If SQL Server changes domains, then you'll need to have trust relationships in AD with those domains.</s>
<s>[INST]CREATE INDEX <index_name> ... WITH (DROP_EXISTING = ON, ONLINE = ON) Hi All, >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) I am trying to understand the behavior of CREATE INDEX WITH (DROP_EXISTING = ON). I currently have a very active table with approximately 45 million rows. There is NO clustered index on this table. There is a non-clustered index that currently looks like this: - CREATE NONCLUSTERED INDEX IX_NC_01 on my_table (Col1); I would like to modify the index by adding an include clause: - CREATE NONCLUSTERED INDEX IX_NC_01 on my_table (Col1) Include (Col2) WITH (DROP_EXISTING = ON, ONLINE = ON) I want this action to be as non-intrusive as possible. I have read this snip from the documentation: >*The DROP_EXISTING clause will not sort the data again if the same index key columns are used in the same order and with the same ascending or descending order, unless the index statement specifies a nonclustered index and the ONLINE option is set to OFF. If the clustered index is disabled, the CREATE INDEX WITH DROP_EXISTING operation must be performed with ONLINE set to OFF. If a nonclustered index is disabled and is not associated with a disabled clustered index, the CREATE INDEX WITH DROP_EXISTING operation can be performed with ONLINE set to OFF or ON.* Questions: 1. Will the old version of the index be available while the statement is running? 2. Please explain the interaction between ONLINE=ON and DROP_EXISTING=ON. My understanding of this is that I should include both clauses. 3. Will I increase locking/blocking while the statement is running? Thank you for your help. --Dan [/INST]Will the old version of the index be available while the statement is running? Yes. > Please explain the interaction between ONLINE=ON and DROP_EXISTING=ON. My understanding of this is that I should include both clauses. I think so too. ONLINE = ON means that you want the table to be available while the CREATE INDEX operation is running. DROP_EXISTING = ON, means that you want to create a new index with the same name, without first dropping the existing index. This is particularly powerful when redefining a clustered index, since this saves you from one round of updating all the non-clustered index. But as the BOL topic says, you may also get the gain of that SQL Server is able to use the existing sort order when all you do is to add an included column. > Will I increase locking/blocking while the statement is running? Yes. While it is an ONLINE operation, Sch-M (schema modification) locks are taken on two occasions: once when the operation starts, once when it completes. These locks are for metadata operations and are usually shortlived. However, if there is a long-running query, this query will block the Sch-M lock, and the request for the Sch-M will block all other processes from accessing the table. Some operations has a WAIT_AT_LOW_PRIORITY option to avoid this issue, but I can't see it for CREATE INDEX. Thus, you may not want to run this command during periods when the table is really busy. Then again, if most queries are short, this is unlikely to be an issue. During the it actually builds in the index, no locks are held.</s>
<s>[INST]what caused the previous CPU spike Good Morning, We got a CPU spike alert. When I went to the server and checked, CPU was fine. I want to know what caused the previous spike. Could you please let me know.[/INST]There is no way to look into the past. You would have to see it when it happens. However, it is perfectly normal for SQL Server to use 100% CPU for short periods of time. This is not something you should be alerting on instantly.</s>
<s>[INST]SUM Over Partition Hi, I have the below SUM that almost gives me what I need, but not fully and wondered if anyone can help please. sum(c.comp_amount) over (partition by a.comp_number , c.start_date, [TD_numeric] ) * ([TD_numeric]/100) as comp_value The problem I have is the variable [TD_numeric] having '0' values so when looking to * [TD_numeric] where it has a 0, it's obviously not going to return any values. However, I need it to essentially include an else, so where [TD_numeric] is '0' then bring back this calculation: sum(c.comp_amount) over (partition by a.comp_number , c.start_date) Any idea if this can be done please? [/INST]Your description can be implemented in this manner:  *case TD_numeric when 0 then ... else ... end as comp_value* Replace '...' with corresponding sums.</s>
<s>[INST]WHERE clause still returning non selected data Hi, I have the following WHERE clause which isn't working and I'm not too sure why. I have explicitly stated to return select data, but if I use the 'e.cust_field' as an example, it's returning values not specified and I don't know why example '2'. where a.comp = '0' and a.mort_code like '%1/%' and c.start_date >= '2020-01-01' and c.start_date <= '2020-12-31' and substring(a.cust_no,3,7) <> 'TMU787' and e.cust_table = '12' and e.cust_field in ('1','3','7','17','21','29','32','35') and e.cust_text <> '1258 testing' Any idea why please?[/INST], The unselected data is returned because those data actually satisfy the conditions behind WHERE. Maybe this is what you want: and (e.cust_field='1' or e.cust_field='3' or e.cust_field='7'or e.cust_field='17' or e.cust_field='21'or e.cust_field='29'or e.cust_field='32' or e.cust_field='35') If you have any question, please feel free to let me know.</s>
<s>[INST]Query optimization A query is running very slow with wait type dirty_page_table_lock. How to fix this? please help.[/INST]the link sreejukg provided opens for me. I copy/pasted some of the text from the page below for your convenience. Install the latest SP or CU if you are not already done so. > KB4163087 - FIX: Performance is slow for an Always On AG when you process a read query in SQL Server > SQL Server 2016 Developer SQL Server 2016 Enterprise More... > Symptoms > Assume that you have an Always On Availability Group (AG) in SQL Server 2016 and 2017. When you process a read query on a secondary replica, the performance might be much slower than the primary replica due to frequent DIRTY_PAGE_TABLE_LOCK waits. > Cause > This issue occurs because of contention between the read query and the redo thread, and because the table is locked. > Resolution > This fix is included in the following updates for SQL Server: > Cumulative Update 8 for SQL Server 2017 > Cumulative Update 1 for SQL Server 2016 Service Pack 2 > Cumulative Update 9 for SQL Server 2016 Service Pack 1 > Workaround > To work around this issue you can use a single redo thread instead of a parallel redo thread by enabling Trace Flag 3459. > More Information > When read-only queries are running on a readable secondary replica, query threads attempt to apply pending log redo operations and need to collaborate with redo worker threads with DIRTY_PAGE_TABLE_LOCK waits, which can be frequently generated and slow down both redo and query performance if there are concurrent redo workloads. The performance issue associated with DIRTY_PAGE_TABLE_LOCK wait is addressed in the cumulative update release for SQL Server 2016 SP and SQL Server 2017 mentioned in this article.</s>
<s>[INST]SQL Server allow snapshot isolation two snapshot isolation transaction , and doing the update on the same records , will the first transaction blocking the 2nd transaction ?[/INST]Data modifications against disk-based tables acquire locks regardless of transaction isolation level. So a second session attempting to update rows modified by the first session will be blocked until the first session performs a commit or rollback.</s>
<s>[INST]How to add mapped to in table trade codes where mapped from exist ? I work on SQL server 2012 I face issue I can't insert mapped to into table trade codes where mapped from exist on table trade code so firstly I will get MapCodeTypeFrom and MapCodeValueFrom from table settings second i will search on table tradecodes for MapCodeTypeFrom and MapCodeValueFrom if MapCodeTypeFrom and MapCodeValueFrom exist on table trade Codes then add MapCodeTypeTo and MapCodeValueTo for every part that meaning every part have MapCodeTypeFrom and MapCodeValueFrom on table TradeCodes must have MapCodeTypeTo and MapCodeValueTo with another meaning every part must have two rows first row for MapCodeTypeFrom and MapCodeValueFrom second row for MapCodeTypeTo and MapCodeValueTo create table #settings ( MapId int, MapCodeTypeFrom nvarchar(50), MapCodeValueFrom int, MapCodeTypeTo nvarchar(50), MapCodeValueTo int ) insert into #settings(MapId,MapCodeTypeFrom,MapCodeValueFrom,MapCodeTypeTo,MapCodeValueTo) values (1222,'ECCN',9910,'HTS',9920), (1222,'Hom',9950,'VOM',9960) --DROP TABLE #TradeCodes create table #TradeCodes ( PartId int, CodeType nvarchar(50), Code int, ) insert into #TradeCodes(PartId,CodeType,Code) values (1334,'ECCN',9910), (1971,'ECCN',9910), (2050,'ECCN',9910), (3000,'VOM',9950), (3600,'VOM',9950), (3700,'VOM',9950) final rows must added on table trade codes that represent mapped to is : PartId CodeType Code 1334 HTS 9920 1971 HTS 9920 2050 HTS 9920 3000 VOM 9960 3600 VOM 9960 3700 VOM 9960 mapped to will added in case of mapped from code type and value Exist on table trade codes [/INST]Should the CodeType is "Hom" instead of "VOM" for PartId 3000, 3600 and 3700? INSERT INTO #TradeCodes SELECT t.PartId, s.MapCodeTypeTo, s.MapCodeValueTo FROM #settings AS s INNER JOIN #TradeCodes AS t ON t.CodeType = s.MapCodeTypeFrom AND t.Code = s.MapCodeValueFrom; SELECT * FROM #TradeCodes;</s>
<s>[INST]How to filter my data in the Query I have a set of data, some 18000 posts. They are either "Server" or "Workstations". If they are servers, the OperatingSystem contains the word server. If they are Workstations, the OperatingSystem *DOES NOT* contains the word server. I really need to be able to filter in 3 different values: 1. All - OperatingSystem LIKE '%' 2. Servers - OperatingSystem LIKE '%SERVER%' 3. Workstations - OperatingSystem NOT LIKE '%SERVER%' These filters work but how do I incorporate them in my rather simple query, so that I can control the filtered results with a variable? My very simple test query: DECLARE @OSTYPE NVARCHAR(15) SET @OSTYPE = 'SERVER' SELECT distinct OperatingSystem FROM v_Some_Odd_View order by OperatingSystem I have tried nested IF and CASE in the WHERE clause. But hours of testing and googling didn't help me and I'm quite sure that I'm missing something minor and completely obvious. My unfiltered result: Microsoft Windows 10 Enterprise Microsoft Windows 10 Pro Microsoft Windows 7 Enterprise Microsoft Windows Server 2008 R2 Enterprise Microsoft Windows Server 2008 R2 Standard Microsoft Windows Server 2012 R2 Datacenter Microsoft Windows Server 2012 R2 Standard Microsoft Windows Server 2016 Datacenter Microsoft Windows Server 2016 Standard Microsoft Windows Server 2019 Datacenter Microsoft Windows Server 2019 Standard Microsoft® Windows Server® 2008 Enterprise Microsoft® Windows Server® 2008 Standard My simple Query for SERVER OS, only: DECLARE @OSTYPE NVARCHAR(15) SET @OSTYPE = 'SERVER' SELECT distinct OperatingSystem FROM v_Some_Odd_View Where OperatingSystem Like '%' + @OSTYPE + '%' order by OperatingSystem Maybe I'm Googeling with the wrong words. Maybe I'm missing the most obvious thing in the world. Please point me in the right direction. [/INST]It is not clear to me how you want the search to work, but maybe this: WHERE (@OSTYPE = 'ALL') OR (@OSTYPE = 'SERVER' AND OperatingSystem LIKE '%SERVER%') OR (@OSTYPE = 'WORKSTATION' AND OperatingSystem NOT LIKE '%SERVER%')</s>
<s>[INST]SQL Server Standard edition license support linked server feature? 1. Does MSSQL server standard edition support server link feature? 2. I need to create a server link between 2 database server in the cloud. 3. if one server is on enterprise edition and another is on standard edition, can the server link be created. [/INST]Linked Servers are not edition dependent. You can create a Linked Server between different versions and editions of SQL Server with no isues.</s>
<s>[INST]SQL Server Default Instances Hello, If I have a standalone server currently running 2016 Developer Edition - Default Instance am I able to install 2017 Developer edition and have another default instance on the same box ? Thanks, V[/INST]there can only be a single default instance.</s>
<s>[INST]error An expression of non-boolean type specified in a context where a condition is expected, near 'MainFeature'. I work on sql server 2012 when run statement below i get error so i need to solve all issues exist on it until statement run An expression of non-boolean type specified in a context where a condition is expected, near 'MainFeature'. so please can you help me if object_id(N'tempdb..#PartAttributes') is not null drop table #PartAttributes if object_id(N'tempdb..#Condition') is not null drop table #Condition if object_id(N'tempdb..#Allfeatures') is not null drop table #Allfeatures if object_id(N'tempdb..#Codes') is not null drop table #Codes create table #Allfeatures ( ZPLID INT, ZFeatureKey nvarchar(20), IsNumericValue int ) insert into #Allfeatures(ZPLID,ZFeatureKey,IsNumericValue) values(75533,'1505730036',0) ----select * from #Condition create table #Condition ( Code nvarchar(20), ZFeatureKey nvarchar(20), ZfeatureType nvarchar(20), EStrat nvarchar(20), EEnd NVARCHAR(10) ) insert into #Condition (Code,ZFeatureKey,ZfeatureType,EStrat,EEnd) values ('8535400000','1505730036',NULL,'>1000',' '), ('8535400000','1505730036',NULL,'MainFeature',' '), ('8535400000','1505730036',NULL,'N/A',' '), ('8535400000','1505730036',NULL,NULL,' ') CREATE TABLE #PartAttributes ( PartID INT, ZFeaturekEY NVARCHAR(20), AcceptedValuesOption_Value INT, Name nvarchar(20) ) insert into #PartAttributes(PartID,ZFeaturekEY,AcceptedValuesOption_Value) values (4977941,1505730036,1.2), (4977936,1505730036,280), (4977935,1505730036,100), (4979054,1505730036,24), (4979043,1505730036,30) DECLARE @Sql nvarchar(max) DECLARE @ConStr nvarchar(max) SET @ConStr= STUFF((SELECT CONCAT(' Or (PM.ZfeatureKey= ', CC.ZfeatureKey , ' And AcceptedValuesOption_Value ' , CAST(EStrat AS NVARCHAR(2500)) , IIF(EEnd='','',CONCAT(' And AcceptedValuesOption_Value ',EEnd)),')') FROM #Condition CC INNER JOIN #Allfeatures AL ON AL.ZfeatureKey = CC.ZfeatureKey FOR XML PATH(''), TYPE).value('(./text())[1]','varchar(max)'),1,3,'') ---EXE(@ConStr) -- print @ConStr SET @Sql= CONCAT(' SELECT PartID, Code, Count(1) as ConCount FROM #PartAttributes PM INNER JOIN #Condition Co ON Co.ZfeatureKey = PM.ZfeatureKey ', 'Where 1=1 and (', @ConStr, ' ) Group By PartID,Code ' , ' Having Count(1)> = ',(SELECT COUNT(1) FROM #Condition)) --print @SQL EXEC (@SQL) so how to solve issues until query run [/INST]if you face this kind of issue, you could consider different conditions when you would like to concatenate one string. What is the expected output of @ConStr if EStrat is 'N/A' or NULL? Please refer below example: DECLARE @Sql nvarchar(max) DECLARE @ConStr nvarchar(max) SET @ConStr= STUFF((SELECT CONCAT(' Or (PM.ZfeatureKey= ', CC.ZfeatureKey , ' And '+ case when PATINDEX('%[><=]%', EStrat)>0 then 'AcceptedValuesOption_Value ' when EStrat is null then 'cast(AcceptedValuesOption_Value as varchar(100)) ' else 'cast(AcceptedValuesOption_Value as varchar(100))=' end, case when PATINDEX('%[><=]%', EStrat)>0 then CAST(EStrat AS NVARCHAR(2500)) when EStrat is null then ' is null ' else ''''+CAST(EStrat AS NVARCHAR(2500)) +'''' end , IIF(EEnd='','',CONCAT(' And AcceptedValuesOption_Value ',EEnd)),')') FROM #Condition CC INNER JOIN #Allfeatures AL ON AL.ZfeatureKey = CC.ZfeatureKey FOR XML PATH(''), TYPE).value('(./text())[1]','varchar(max)'),1,3,'') --print @ConStr SET @Sql= CONCAT(' SELECT PartID, Code, Count(1) as ConCount FROM #PartAttributes PM INNER JOIN #Condition Co ON Co.ZfeatureKey = PM.ZfeatureKey ', 'Where 1=1 and (', @ConStr, ' ) Group By PartID,Code ' , ' Having Count(1)> = ',(SELECT COUNT(1) FROM #Condition)) --print @SQL EXEC (@SQL) If you have any other issue, please provide more sample data and expected output.</s>
<s>[INST]Looking for script to for login creations and assigning permissions. Hi Experts, Does anybody has a script or stored procedure which takes care of login creation, user creation and adding roles and permissions. Basically, looking for script which does the following : We will pass loginame, login type, db name, db_rolename as 4 parameters to stored procedure/sql script. It should check for existence of the login, if login doesn't exists, then create a windows login or a sql login based on the login type. Also, based on the db name which is passed as parameter or input value, it should go ahead and create the user in that database and assign the db_role passed as parameter. Login type valid values : WINDOWS_LOGIN, SQL_LOGIN Thanks in advance. Sam [/INST]create or alter proc dbo.usp_login_creation @login varchar(100), @login_type varchar(20), @dbname varchar(50), @dbrole varchar(50) as begin BEGIN TRY IF (SUSER_ID(@login) IS NOT NULL) BEGIN PRINT ' LOGIN ALREADY EXISTS' RETURN ELSE BEGIN DECLARE @sqlcmd VARCHAR(MAX); SET @sqlcmd = ' USE [master]; CREATE LOGIN ' + QUOTENAME(@login) + CASE WHEN @login_type = 'Windows' THEN ' FROM WINDOWS' ELSE 'WITH PASSWORD=N''SunRise#123''' END + ' WITH DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=ON '; EXEC(@sqlcmd); SET @sqlcmd = ' USE ' + QUOTENAME(@dbname) + '; CREATE USER '+ QUOTENAME(@login) +' FOR LOGIN '+ QUOTENAME(@login) +'; ALTER ROLE [db_owner] ADD MEMBER ' + QUOTENAME(@login) +'; '; EXEC(@sqlcmd); TRY BEGIN CATCH THROW; CATCH</s>
<s>[INST]SQL Server Connection from a PLC Hello, my question relates to the connection string being sent from a PLC. If the connection fails, will the connection be re-established while the statement is present, or will the database only try to connect once? Thank you for your support Best regards, Kai [/INST]It's the task of the developer, how his application re-acts when the connections fails or gets interupt. SQL Server do nothing is this way, it's the client part.</s>
<s>[INST]SQL Memory - Multiple instances same server Hello, If I have 1 database server with 38 gb of memory and I have installed 2 SQL instances , how to do I split the memory between the 2 instances while leaving 20% memory for the OS ? Thanks, V[/INST]You will need to do this manually, as the two instances are not aware of each other. With 38GB available, you are looking at about 30GB available to split between the two. The easy thing is to assign a max memory of 15GB to each, but chances are they don't have equal workloads, so you will want to adjust accordingly. HTH</s>
<s>[INST]How to Run Powershell Command in SQL Sever Agent Job I have a variable in the powershell command. We are considering to run it in SQL Agent job step 1. However I always get the below error. Command: $a = $(Get-Date).AddMonths(1).ToString("yyyyMM") Write-Output "output____$a" Error message: Unable to start execution of step 1 (reason: The job step contains tokens. For SQL Server 2005 Service Pack 1 or later, you must use the appropriate ESCAPE_xxx macro to update job steps containing tokens before the job can run.). The step failed.[/INST]The SQL Agent job thinks "$(Get-Date)" is an unrecognized token. $() is reserved for tokens in SQL Agent. The simplest answer is to do: $d = Get-Date $a = $d.AddMonths(1).ToString("yyyyMM")</s>
<s>[INST]SQL Server 2012 - Does killing a spid causing a block result in possible data loss? Good Day SQL Server Guru's and Tech's, I am being hounded by developers and their management to kill processes locking during a bulk load and users utilizing the front end application. I've recommended disabling indexes and/or dropping and rebuilding them but the users and DML bulk load statements have to occur at the same time. This requires us to adjust fill factor, increase update statistics and sometimes defrag the database. It also requires DBA Team to kill spids which I am not a fan of doing because I feel the possibility of data loss is evident. Please let me know your thoughts and recommendations if any. I found only one article on this online so I am hoping to get more backing from the DBA community. Thank you. Best Regards - Stay safe and healthy, Frank[/INST]Bulk load operations normally require a full table lock. There is no way around that. The best solution for bulk load operations is to do them after hours. If you are trying to use a table, while it is being loaded, you either need to wait for the load to finish. or stop the load and have it roll back to the previous state.</s>
<s>[INST]Aggregation weekly data from daily field CREATE TABLE #MYSRC ( ID_1 VARCHAR(10), ID_2 int, ID_3 VARCHAR(10), Pay1 varchar(6), Pay2 varchar(6), Status varchar(10), FileDate DATE ) --- SOME MORE detail INFO about data --- WE HAVE ABOUT 2 YEARS WORTH OF DAILY FEEDS DATA LOADED TO ONETABLE(MYSRC) last column FileDate shows what day is the file, the granularity here is daily. --- USUALLY EACH DAY FILE HAVE ABOUT 30K RECORDS, IN WHICH IT INCLUDES OLD RECORDS AS IS, NEW ENTRIES ADDED (by considering id1,id2,id3 combination) , FOR SOME MEMBERS IT MAY CHANGE OTHER COLUMN VALUES. --- WE FOUND MEMBER BASED ON THREE id FIELDS, IF ID_1,2,3 CHANGES THEN IT IS CONSIDER AS NEW MEMBER. --- HERE WOULD LIKE TO KNOW HOW MANY NEWMEMBERS WERE ADDED PER EACH week (weekly AGGREGATION) ---Inserts 5 records in that file, 3 old 2 new (in 2 one is just id change one is INSERT INTO #MYSRC VALUES ('3120', 250, '3241', '120.75','0.00','EN-25', '09/20/2021') -- exist same set (id1,2,3) in earlier data, so not a new member for Sep INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '09/20/2021') -- exist same set (id1,2,3) in earlier data, so not a new member for Sep INSERT INTO #MYSRC VALUES ('3122', 250, '3243', '20.75','0.00','EN-25', '09/20/2021') -- exist same set (id1,2,3) in earlier data, so not a new member for Sep INSERT INTO #MYSRC VALUES ('7120', 250, '3241', '120.75','0.00','EN-50', '09/03/2021') --New RECORDS because of ID1 change, INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '09/03/2021') ---Old RECORDS/member INSERT INTO #MYSRC VALUES ('1122', 250, '3243', '20.75','0.00','EN-25', '09/02/2021') --old record INSERT INTO #MYSRC VALUES ('1123', 252, '3244', null,null,'EN-25', '09/02/2021') --old record/member INSERT INTO #MYSRC VALUES ('1122', 27, '3243', '20.75','0.00','EN-25', '09/01/2021') --New Set of ID1,2,3 not exist in earlier data so count it as new member for SEP INSERT INTO #MYSRC VALUES ('1123', 252, '3244', null,null,'EN-25', '09/01/2021') --New Set of ID1,2,3 not exist in earlier data so count it as new member for SEP ---- August Data below - FileDate (last column) INSERT INTO #MYSRC VALUES ('3120', 250, '3241', '120.75','0.00','EN-25', '08/31/2021') -- exist same set (id1,2,3) in earlier data, so not a new member for Aug INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '08/31/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for Aug INSERT INTO #MYSRC VALUES ('3122', 250, '3243', '20.75','0.00','EN-25', '08/31/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for Aug INSERT INTO #MYSRC VALUES ('3120', 250, '777', '120.75','0.00','EN-25', '08/30/2021') --New Set of ID1,2,3 not exist in earlier data so count it as new member for Aug INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '08/30/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('3120', 250, '3241', '120.75','0.00','EN-25', '08/29/2021') -- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '08/29/2021') -- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('3122', 250, '3243', '20.75','0.00','EN-25', '08/29/2021') -- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('3120', 250, '888', '120.75','0.00','EN-25', '08/18/2021') ---same set (id1,2,3) not exist earlier, appeared first in Aug 2021. so count it INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '08/17/2021')--- exist same set (id1,2,3) in earlier data, so not a new member for Aug INSERT INTO #MYSRC VALUES ('1121', 37, '3242', null,'3.00','FU-25', '08/11/2021') --- New Set of ID1,2,3 not exist in earlier data so count it as new member for AUG INSERT INTO #MYSRC VALUES ('3122', 36, '100', '20.75','0.00','EN-25', '08/11/2021') ---New Set of ID1,2,3 not exist in earlier data so count it as new member for AUG ---- July Data below INSERT INTO #MYSRC VALUES ('3120', 250, '3241', '120.75','0.00','EN-25', '07/31/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '07/31/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('9122', 250, '3243', '20.75','0.00','FU-25', '07/31/2021') -- New Set of ID1,2,3 not exist in earlier data so count it as new member for July INSERT INTO #MYSRC VALUES ('3120', 250, '777', '120.75','0.00','FU-25', '07/20/2021') -- New Set of ID1,2,3 not exist in earlier data so count it as new member for July INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '07/20/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('3120', 250, '3241', '120.75','0.00','EN-25', '07/10/2021') -- New Set of ID1,2,3 not exist in earlier data so count it as new member for July INSERT INTO #MYSRC VALUES ('6121', 251, '3242', null,'3.00','FU-25', '07/10/2021') -- New Set of ID1,2,3 not exist in earlier data so count it as new member for July INSERT INTO #MYSRC VALUES ('3122', 250, '3243', '20.75','0.00','FU-25', '07/10/2021') -- New Set of ID1,2,3 not exist in earlier data so count it as new member for July INSERT INTO #MYSRC VALUES ('3120', 250, '888', '120.75','0.00','EN-25', '07/05/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('5121', 251, '3242', null,'3.00','FU-25', '07/05/2021')-- New Set of ID1,2,3 not exist in earlier data so count it as new member for July INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','FU-25', '07/01/2021') --- exist same set (id1,2,3) in earlier data, so not a new member for July INSERT INTO #MYSRC VALUES ('4122', 250, '100', '20.75','0.00','EN-25', '07/01/2021') -- New Set of ID1,2,3 not exist in earlier data so count it as new member for July ---- Jun INSERT INTO #MYSRC VALUES ('3120', 250, '888', '120.75','0.00','EN-25', '06/05/2021') INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','EN-25', '06/05/2021') INSERT INTO #MYSRC VALUES ('1121', 251, '3242', null,'3.00','FU-25', '06/01/2021') INSERT INTO #MYSRC VALUES ('3122', 250, '100', '20.75','0.00','EN-25', '06/01/2021') --- assume jun 2021 is Starting population expected output as below first column week values (for every week current to min(filedate) week. i just choose a format but at your convenience pleas choose anyway you like., second column is New numbers as explained above only counts new numbers byid1, id2, id3 fields values not exist earlier third column out of second column (new members) how many were first two characters of status column = "FU" then count else 0 Forth column out of second column (new members) how many were first two characters of status column = "EN" then count else 0 Week NewMembers FUMembersCounts EUMembersCount Oct-03-2021 To Oct-09-2021 0 0 0 Sep-26-2021 To Oct-02-2021 0 0 0 Sep-19-2021 To Sep-25-2021 0 0 0 Sep-12-2021 To Sep-18-2021 0 0 0 Sep-05-2021 To Sep-11-2021 0 0 0 Aug-30-2021 To Sep-04-2021 5 3 2 please help me Thank you Asiti [/INST]I updated the script based on your further requirements. I use the month name based on the week start date, but you can change it to the week end date if you prefer it. You can also remove the LEFT() function from the month name to get the whole month name, i.e., 2021-September instead of 2021-Sep: DECLARE @startDate datetime; DECLARE @endDate datetime; SELECT @startDate = MIN(FileDate), @endDate = MAX(FileDate) FROM #MYSRC; ;WITH CTE_Calendar_Date AS ( SELECT @startDate AS [Date] UNION ALL SELECT DATEADD(day, 1, [Date]) AS [Date] FROM CTE_Calendar_Date WHERE [Date] <= @endDate ), CTE_Calendar_WeekNumber AS ( SELECT [Year], WeekNumber, MIN([Date]) AS WeekStart, MAX([Date]) AS WeekEnd FROM ( SELECT YEAR([Date]) AS [Year], DATEPART(WEEK, [Date]) AS WeekNumber, [Date] FROM CTE_Calendar_Date ) AS d GROUP BY [Year], WeekNumber ), CTE_New_Number AS ( SELECT * FROM ( SELECT ID_1, ID_2, ID_3, [Status], Year(FileDate) AS [Year], DATEPART(WEEK, FileDate) AS WeekNumber, ROW_NUMBER() OVER(PARTITION BY ID_1, ID_2, ID_3 ORDER BY FileDate) AS Ranked FROM #MYSRC ) AS t WHERE t.Ranked = 1 ) -- Month name is based on WeekStart date which can be changed to WeekEnd -- Remove LEFT() function to get whole month name SELECT CAST(c1.[Year] AS char(4)) + '-' + LEFT(DATENAME(month, c1.WeekStart), 3) AS [Year-MonthName], REPLACE(REPLACE(CONVERT(varchar(12), c1.WeekStart, 107), ', ', '-'), ' ', '-') + ' To ' + REPLACE(REPLACE(CONVERT(varchar(12), c1.WeekEnd, 107), ', ', '-'), ' ', '-') AS [Week], ISNULL(c2.NewMembers, 0) AS NewMembers, ISNULL(FUMembersCounts, 0) AS FUMembersCounts, ISNULL(EUMembersCount, 0) AS EUMembersCount FROM CTE_Calendar_WeekNumber AS c1 LEFT JOIN ( SELECT [Year], WeekNumber, COUNT(*) AS NewMembers, SUM(CASE WHEN LEFT([Status], 2) = 'FU' THEN 1 ELSE 0 END) AS FUMembersCounts, SUM(CASE WHEN LEFT([Status], 2) = 'EN' THEN 1 ELSE 0 END) AS EUMembersCount FROM CTE_New_Number GROUP BY [Year], WeekNumber ) AS c2 ON c1.[Year] = c2.[Year] AND c1.WeekNumber = c2.WeekNumber ORDER BY c1.[Year] DESC, c1.WeekNumber DESC</s>
<s>[INST]sql table sequence update help Hi, I have a column named \[list\] which I need to update with sequence number partitioned by \[id\] order by \[comment_timestamp\] It works in a select statement: SELECT row_number() over (partition by id order by comment_timestamp) FROM dbo.comments but I don't know how to put this in an update statement? The script for the table look like this CREATE TABLE \[dbo\].\[comments\]( \[id\] \[int\] NOT NULL, \[list\] \[int\] NULL, \[Comment\] [varchar] NULL, \[domain\] [varchar] NULL, \[comment_timestamp\] [datetime2] NULL ) ON \[PRIMARY\] TEXTIMAGE_ON \[PRIMARY\] GO I understand this might be very easy but could someone please assist? Appreciate all help [/INST]Check this command: update t set list = rn from ( select list, row_number() over (partition by id order by comment_timestamp) as rn from dbo.comments ) t If you are interested. you will also find an alternative based on "CTE".</s>
<s>[INST]positive edge Hi every one , i wanted to build a positive edge with a variable that i named @Prozessstart. this is my programm Create TRIGGER [dbo].[tinsert] ON [dbo].[TBL_LiveData] AFTER UPDATE As DECLARE @Prozessstart integer; Prozessstart = 0 IF (SELECT dbo.TBL_LiveData.Value FROM dbo.TBL_LiveData WHERE dbo.TBL_LiveData.ConfigID = 251) =0 BEGIN @Prozessstart := 0 ; END IF ((SELECT dbo.TBL_LiveData.Value FROM dbo.TBL_LiveData WHERE dbo.TBL_LiveData.ConfigID = 251) =1) AND @Prozessstart < 1 BEGIN @Prozessstart <= @Prozessstart + 1 INSERT INTO .... END but i recieve this error message , Message 102, level 15, status 1, procedure tinsertV9, line 7 [Batchstart line 7]. Incorrect syntax near "@processstart". Message 102, level 15, status 1, procedure tinsertV9, line 12 [Batchstart line 7]. Wrong syntax near "@processstart". Message 102, level 15, status 1, procedure tinsertV9, line 18 [Batchstart line 7]. Wrong syntax near "@processstart". Message 102, level 15, status 1, procedure tinsertV9, line 26 [Batchstart line 7]. Incorrect syntax near "END". can anyone please help me ? [/INST]Try removing ':' and '<' and use *SET*: set @Prozessstart = 0 set @Prozessstart = @Prozessstart + 1 (or *set @Prozessstart += 1*). You also have *Prozessstart = 0* which probably must be *set @Prozessstart = 0*. And something is wrong before the *END* line.</s>
<s>[INST]SQL - Calling SProc located in Server2 from Server1 using LinkedServer --> Need to Pass Table results from Server1 as Input parameter to this SProc Need help on below: I need to execute a Stored procedure located in Server2 from Server1 like below: -- Query on Server1 EXEC [**LinkedServer2**].DatahubDB.dbo.usp_Calcs @ClmsPaid Table, @Period = '2021' For the first parameter @ClmsPaid, i need to pass results of a table with few columns in it which is available in Server1(This is where i am running the EXEC statement). Is it possible, if yes, how would i do it?[/INST]I was a little lazy, and assumed that you might already have worked with XML data type. It is after all, a decently widely used feature. The part: SELECT [MedNo], [ClmAmt], [fy_end], [fy_start] FROM @xml.nodes(''/root/data'') AS T(c) Should read: SELECT T.c.value('@MedNo', 'varchar(50)') AS MedNo, T.c.value('@ClmAmt', 'numeric(11,2)') AS ClmAmt, T.c.value('@fy_end', 'date') AS fy_end, T.c.value('@fy_start', 'date') AS fy_start FROM @xml.nodes('/row') AS T(c)</s>
<s>[INST]update table column based on sub table multiple value Hi, I have a Main table and Sub table like below create table Main (Code nvarchar(10), Amount decimal(18,2), NewAmount decimal(18,3)) create table Sub (Code nvarchar(10), Price decimal(18,2)) insert into Main values ('1111', 100,0) insert into Sub values ('1111',10) insert into Sub values ('1111',20) insert into Sub values ('1111',100) --update T Set T.NewAmount=0 from Main T inner join price P on T.code=P.Code select * from Main select * from Sub drop table Main drop table Sub i need to update main table NewAmount column based on Sub table Price column if Amount in Main table matched with price column in Sub Table then NewAmount in Main table should be Amount Value otherwise '0' value[/INST]Check a possibility: update m set NewAmount = isnull(s.Price, 0) from Main m left join Sub s on s.Code = m.Code and s.Price = m.Amount (If *'s.Code = m.Code'* is not needed, then remove it). Another possibility can be based on "CTE".</s>
<s>[INST]Creating an Identical PUBLIC Role in SQL Server 2012 and Above Hello, We have a database security scan report that shows vulnerabilities relating to SELECT and EXECUTE permissions granted to PUBLIC role (server and database role). It also has a warning about changes to the PUBLIC role may be harmful. We are thinking of creating a new user defined role besides assigning the same permissions that PUBLIC role has and adding all the user accounts to the newly created user defined role to circumvent the database scan report which only looks at PUBLIC role. Is there a script that we can do that? I did see one script that would list out all the PUBLIC role permissions besides showing REVOKE, but before revoking these permissions, if we can map the current PUBLIC role permissions (both sql server and at the database level) to the newly created user defined role, that would be awesome. Any help/input will be greatly appreciated. Thanks. Victor[/INST]If you have a script with all REVOKE statements to run, you can do some find/replace to change that to GRANT those permissions to this new role. Although I would be a little careful with such a lockdown craze. Most system procedures checks for permissions themselves, so the permissions to public are not that problematic. And there are some catalog procedures that are used by APIs, so revoking permissions on these can break quite a few things.</s>
<s>[INST]Giving space after comma in sql server Hello All I am new to sql. I need to give a space after comma in my employee name . Please suggest how to do. Data : Smith,Micheal Ben,Jeff Output : Smith, Micheal Ben, Jeff[/INST]Try a query: select replace(replace(MyColumn, ', ', ','), ',', ', ')</s>
<s>[INST]How to delete a column which doees not have a related table? We have some objects in sys.columns that don't have any relating row(s) in sys.objects. The problem is also shown by DBCC CHECKCATALOG. This is what the catalog check reveals: Attribute (object_id=1691153070) of row (object_id=1691153070,column_id=6) in sys.columns does not have a matching row (object_id=1691153070) in sys.objects. **The question is how to delete the columns which don't have any relating object(Table/View...)?** [/INST]For a 15 GB table, it sounds to me that the best option is to build a new database from scripts and copy data over. If you don't want to go this path, I recommend that you open a support case. To clean this up, you will need to perform operations that are undocumented and unsupported. If you would run them on your own, you could void you support options for the future. There is also a risk that you mess things up even more. If you open a support case, a support professional can guide you through the operation, and also record the operation as supported.</s>
<s>[INST]how to create alert when any job add, modify or delete in sql server I have a company they use SQL Server 2016 SE. here multiple DBA owner and they create there requirement basis job and it modify, or delete. that reason we have multiple job in SQL Server, i m not properly monitor to all job. this reason I want to alert when any job create, modify or delete in SQL Server. [/INST]I would try to create the triggers on the table [msdb].[dbo].[sysjobs] for INSERT, UPDATE and DELETE so that the notification emails would be sent out when the job is created, updated or deleted.</s>
<s>[INST]Working with SQL Service Broker Hi, Running SQL Server 2017. I have a requirement to send an email based on certain row conditions in a given table. The email is dynamic, and based on values contained in the row itself. My initial thought was to use an after update trigger, encapsulating the logic to build the email and send it inside the trigger. However, my research has led me to looking at using Service Broker instead. I have read Adam Machanic's workbench series on Service Broker, but am still at a bit of a loss. In essence, I need to know what PKs in the after update trigger meet my condition, so I can build/send an email for each PK. But I'm not sure of how to tackle this from a Service Broker standpoint. I could, at the trigger level, insert the PKs into a staging table and then run a job at intervals to loop through the staging table and do the rest of the processing in the SP called from the job but I would like these emails to be sent as soon as possible after the trigger runs, not necessarily at set intervals. How could I use a Service Broker message to pass the PK to the activation procedure? Or, if I'm way off how would I use Service Broker to accomplish what I want to do? Any suggestions are greatly appreciated! Best Regards B[/INST]Service Broker is certainly an option. The one thing that would hold you back is that there is a hurdle to get started, and if you only use Service Broker in a corner of your application, the cost for maintaining that corner would be high. Then again, Service Broker is quite powerful, and you may find other uses for it in your application, and it is used on a wider basis, knowledge in the team is likely to be higher. In this the example you would do something like: SET @data = (SELECT pkcol FROM inserted FOR XML AUTO) and then send alrt in the SEND statement. The activation procedure would shred the XML to get the PK values. You don't have to use XML - you could sent a comma-separated list. Or, since you ultimately are sending a binary value, you create a varbinary with fixed sizes for the ids.. (If they are integer ids.) However, the normal thing to do is to send XML documents.</s>
<s>[INST]Days between first and second date Hi, I have 2 variables 1. Cust_No 2. Pay_Date Within the table I am using a particular Cust_No and they have 18 records because they have made 18 payments (Pay_Date). What I need to do is work out the time in days between the first Pay_Date and second Pay_date but not sure how to go about doing this. First Date (Pay_Date)= 2020-11-02 Second Date (Pay_Date) = 2020-11-26 So I want my new variable 'Time_to_second_Payment' to show as '24' Any idea on how to capture this information please? [/INST]Hey Bone\_12 , You can use partition query to order the customer by paydate asc So for rownbr= 1 and rownbr=2 would be the 1st and 2nd instance of the payment select *,row_number() over(partition by customer order by paydate Asc)as rowno from table And then use:DateDiff</s>
<s>[INST]Migrate from SQLExpress 2017 to SQLExpress2019 Can I backup a SQL Express 2017 db and restore to SQL Express 2019 or do I need to use the Migration Assistant?[/INST]That should work fine. The purpose of the Migration Assistant is to identify things can potentially could be an issue in the migration. One word of caution though: before you restore the database, make sure that you have applied the most recent Cumulative Update to SQL 2019 which CU13. Keep in mind that when you restore the database, it will remain in compatibiliy level 140. You may want to do. ALTER DATABASE db SET COMPATIBILITY_LEVEL = 150 to get access optimizer enhancements in SQL 2019. Although, there is a small risk that the enhancements may backfire. The one which is likely to have the biggest impact is inlining of scalar UDFs. There were a couple of issues with this change which have been addressed in a couple of CUs. That's why you should make sure that you have CU13 installed before you restore the database.</s>
<s>[INST]take database offline hangs Hi, I have a database in SQL Server 2012 on which I right-clicked and selected Tasks | Take Offline. This opened a dialog box that says "Take database offline - MYSERVERNAME" in the title bar. In the "Details" section of this dialog box, a single action is listed as "Take database MYDATBASENAME offline" with status "In Progress". This has been going on for about a half hour. The dialog box only has a single button labeled "Close". Clicking this button does nothing. Now, the database is not responding to clients (as if it is in fact offline, even though my request action still indicates that it is in progress. I would like to cancel my request, so that the database will be online again and able to serve clients. If anyone can tell me how to do this, I would greatly appreciate it. Thanks and best regards, Paul[/INST]First step: check the status of the database USE master GO SELECT state_desc,* FROM sys.databases where [name] = 'Database_name_come_here' GO If the database is OFFLINE then you can bring it ONLINE using direct queries AND NOT GUI (I don't say the GUI will not work but that you should avoid using it) USE [master] GO ALTER DATABASE [Database_name_come_here] SET ONLINE GO Check the status again. If this is ONLINE the try to use the database and forget about the GUI If there is issue then you need to confirm if the action of taking the database OFFLINE is actually running or this is an issue with the client side -- this will return all the queries which are running now SELECT sqltext.TEXT, req.session_id, req.status, req.command, req.cpu_time, req.total_elapsed_time FROM sys.dm_exec_requests req CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext GO If the query is actually running then the next step is something I cannot recommend you to do, and if you do it then it is on your responsibility, but I would probably simply kill the running query, using the session_id from the above query KILL [session_id] Close the SSMS and re-open it and go back to work Check the status and if needed bring database ONLINE</s>
<s>[INST]what's the difference between peer-to-peer vs merge replication what's the difference between peer-to-peer vs merge replication in sql server ? both support multiple node write . [/INST]I just used google: The main difference is that for merge replication there is only one publisher and one or more subscribers, but in peer-to-peer replication all nodes are both publishers and subscribers I hope that will help you.</s>
<s>[INST]Show month as text Hi, I have a date time field (date_in) 2021-09-15 11:12:58.2220000 and I would like to pull out the month only. I have created a column month(date_in) as date_in_month but the output is 1-12. Any idea how I can see this as Jan - Dec please instead?[/INST]Check an example that uses *FORMAT*: declare @date_in as datetime = '2021-09-15 11:12:58.222' select @date_in, format(@date_in, 'MMM')</s>
<s>[INST]SQL Server: How to find what is attemtping to connect using the sa account Using SQL Server 2019, Windows Server 2016: Checking the event lots I see this event about every minute, sometimes twice a minute: EventData sa Reason: An error occurred while evaluating the password. Its a new server at midnight so I know no person is using it. I have another app installed on the server called ArcGIS Server which is a mapping server but did not setup any db connections using the sa account. Furthermore, the sa account is disabled. How can I find what is attempting to connect using the sa account? Thank you.[/INST]The SQL Server log should include the IP address of the client.</s>
<s>[INST]How to find fragmentation of a single table Good Morning, How How to find fragmentation of a single table?[/INST]How are things going? Please try: DECLARE @db_id INT; DECLARE @object_id INT; SET @db_id = db_id(N'Database_Name'); SET @object_id = OBJECT_ID(N'Table_Name'); SELECT * FROM sys.dm_db_index_physical_stats(@db_id, @object_id, NULL, NULL , 'LIMITED'); GO The LIMITED mode is the fastest mode and scans the smallest number of pages. For an index, only the parent-level pages of the B-tree (that is, the pages above the leaf level) are scanned. For a heap, the associated PFS and IAM pages are examined and the data pages of a heap are scanned in LIMITED mode. The SAMPLED mode returns statistics based on a 1 percent sample of all the pages in the index or heap. Upto 10000 pages this scans all pages. The DETAILED mode scans all pages and returns all statistics and and is considered most heavy scan.</s>
<s>[INST]issue $ separator display when i have only one feature name ? I work on on server 2012 i face issue separator $ display when i have only one feature name for multiple item feature it display correct but one extra separator on start why this happen and how to solve it . it display as below : FeatureName $Zener $Discrete$SOT$Zener **desired result** FeatureName Zener Discrete$SOT$Zener what i try SET @Sql= CONCAT('INSERT INTO dbo.AllData(PartID,Code,CodeTypeID,RevisionID,ZPLID ,ConCount,FeatureName,FeatureValue)',' SELECT PartID,Code,Co.CodeTypeID,Co.RevisionID,Co.ZPLID,Count(1) as ConCount, stuff(( SELECT ''$'' + CAST( CP.ColumnName AS VARCHAR(300)) AS [text()] FROM(SELECT distinct d.ColumnName,C.codeTypeId,C.Code,C.ZfeatureKey from Condition C inner join core_datadefinitiondetails d with(nolock) on C.ZfeatureKey=d.columnnumber INNER JOIN PartAttributes P with(nolock) on P.partid=PM.partid)CP where CP.codeTypeId=Co.codeTypeId and CP.Code=Co.Code ORDER BY CP.ZfeatureKey FOR XML PATH(''''), TYPE ).value(''.'', ''NVARCHAR(MAX)'') , 1, 0, '''') as FeatureName, stuff(( SELECT ''$'' + CAST( CP2.FeatureValue AS VARCHAR(300)) AS [text()] FROM(SELECT distinct P.FeatureValue,C2.codeTypeId,C2.Code,C2.ZfeatureKey FROM Condition C2 with(nolock) INNER JOIN PartAttributes P with(nolock) on C2.ZfeatureKey=P.ZfeatureKey)CP2 where CP2.codeTypeId=Co.codeTypeId and CP2.Code=Co.Code ORDER BY CP2.ZfeatureKey FOR XML PATH(''''), TYPE ).value(''.'', ''NVARCHAR(MAX)'') , 1, 0, '''') as FeatureValue FROM PartAttributes PM INNER JOIN Condition Co ON Co.ZfeatureKey = PM.ZfeatureKey ', 'Where (1=1 and ',@Con , @ConStr,' ) Group By PartID,Code,Co.CodeTypeID,Co.RevisionID,Co.ZPLID ' , ' Having Count(1)>= ',(SELECT COUNT(1) FROM Condition)) EXEC (@SQL) [/INST]Replace all of *"1, 0"* with *"1, 1"*.</s>
<s>[INST]SSMS/ADS Incorrect intellisense with OPENJSON in CTE In SSMS 18.10, and in Azure Data Studio 1.33.1, in a query that uses OPENJSON in a CTE, I get "red squiggles" from Intellisense, in my query. Minimal reproducible example: DECLARE @JsonData VARCHAR(MAX); SET @JsonData = '[ { "SomeValue" : "Hello" }, { "SomeValue" : "There" } ]'; WITH CTEData AS ( SELECT [SomeValue] FROM OPENJSON(@JSonData) WITH ( [SomeValue] VARCHAR(50) '$.SomeValue' ) ) SELECT [SomeValue] FROM CTEData SSMS/ADS "squiggles" the [SomeValue] field with "Invalid column name", but the query runs successfully. I've found that if I "alias" the CTE columns, it seems to resolve the issue: DECLARE @JsonData VARCHAR(MAX); SET @JsonData = '[ { "SomeValue" : "Hello" }, { "SomeValue" : "There" } ]'; WITH CTEData AS ( SELECT [SomeValue] **AS [SomeValue]** FROM OPENJSON(@JSonData) WITH ( [SomeValue] VARCHAR(50) '$.SomeValue' ) ) SELECT [SomeValue] FROM CTEData When I do this, Intellisense sees the columns in the CTE, gives me suggesstions, etc. Is this a known issue, or "by design" or a bug? I'm not thrilled about aliasing columns, especially when I have a lot of them, but it seems to resolve the issue so that's what I'll do for now. Thanks. [/INST]It seems that SQL Server IntelliSense may not recognize the column in the CTE table. You can submit it to the Microsoft feedback as Erland mentioned. Your feedback enables Microsoft to offer the best software and deliver superior services. Appreciate for your understanding.</s>
<s>[INST]SQL: Replacing a drive I have SQL installed on a Hyper-V VM but whoever created it, has made a mess of it. The data drive was originally 250Gb and when the data has outgrown that, rather than increasing the size of the disk, he's added another and spanned the two together to make one larger drive. Within Windows, both drives are set as dynamic and that's what's causing me issues; Veeam backup doesn't seem to like that mode and is unable to back up the VM. My plan is to: 1. Stop SQL services. 2. Create one large drive 3. Change the letter of the existing drive (S becomes T) 4. Give the new drive the letter of the existing drive (S) 5. Restart SQL 6. Get a backup of the VM with Veeam 7. Delete the old drive(s) 8. Pat myself on the back This seems almost too easy - am I missing something? I'll obviously have a full backup and snapshot/checkpoint to begin with and be doing this out of hours, but is there anything that could cause problems? As far as I can tell (server rather than SQL guy here), everything in SQL is done via drive letter rather than a disk ID so, assuming SQL comes back up and the letter is the same, what can go wrong? [/INST]You will have to copy the databases to the new drive, but I guess that you have figured that out. But else I think it should work. But I would certainly test on a copy of the VM first.</s>
<s>[INST]Microsoft.Data.Sqlite SqliteTransaction question Hi, I'm experimenting with converting some Sqlite code to Microsoft.Data.Sqlite, including this: using (SqliteTransaction transaction = con.BeginTransaction()) { //for (int j = 0; j < _totalItems; j++) //{ using (SqliteCommand cmd = con.CreateCommand()) { cmd.CommandText = @"INSERT INTO ProductData (ProductId, ProductName, OrderDate, OrderNumber, Unused1, Unused2, DimReady) VALUES (@productId, @productName, @orderDate, @orderNumber, @unused1, @unused2, @dimReady)"; for (int j = 0; j < _totalItems; j++) { cmd.Parameters.Add(new SqliteParameter("@productId", _dataFields[j][0])); cmd.Parameters.Add(new SqliteParameter("@productName", _dataFields[j][1])); cmd.Parameters.Add(new SqliteParameter("@orderDate", _dataFields[j][2])); cmd.Parameters.Add(new SqliteParameter("@orderNumber", _dataFields[j][3])); cmd.Parameters.Add(new SqliteParameter("@unused1", _dataFields[j][4])); cmd.Parameters.Add(new SqliteParameter("@unused2", _dataFields[j][5])); cmd.Parameters.Add(new SqliteParameter("@dimReady", _dataFields[j][6])); cmd.ExecuteNonQuery(); } } transaction.Commit(); con.Close(); } I get an error message if I use it like it is though. If however I move the "for" iterator up as shown (commented out), it works, for whatever reason. I'm not sure though if that's the best way to do it - I'm thinking about performance here, and if there may be a better solution? It's reasonably fast though, 18.000 rows are inserted in a few seconds. Thanks, Rich [/INST]You keep adding the same parameters to the cmd. I would clear them after you execute the query. Try changing your code to this using (SqliteCommand cmd = con.CreateCommand()) { cmd.CommandText = @"INSERT INTO ProductData (ProductId, ProductName, OrderDate, OrderNumber, Unused1, Unused2, DimReady) VALUES (@productId, @productName, @orderDate, @orderNumber, @unused1, @unused2, @dimReady)"; for (int j = 0; j < _totalItems; j++) { cmd.Parameters.Add(new SqliteParameter("@productId", _dataFields[j][0])); cmd.Parameters.Add(new SqliteParameter("@productName", _dataFields[j][1])); cmd.Parameters.Add(new SqliteParameter("@orderDate", _dataFields[j][2])); cmd.Parameters.Add(new SqliteParameter("@orderNumber", _dataFields[j][3])); cmd.Parameters.Add(new SqliteParameter("@unused1", _dataFields[j][4])); cmd.Parameters.Add(new SqliteParameter("@unused2", _dataFields[j][5])); cmd.Parameters.Add(new SqliteParameter("@dimReady", _dataFields[j][6])); cmd.ExecuteNonQuery(); cmd.Parameters.Clear();</s>
<s>[INST]SQL grouping Hi all I'm trying to create a query that lists a group of records only when the last record of the group doesn't have a specific field value (trans<>'delete') key access trans date (mm/dd/yyyy) 1 adt add 01/01/2020 2 adt change 01/02/2020 3 adt delete 01/03/2020 4 btt add 01/01/2020 5 btt change 01/02/2020 6 cdt add 01/01/2020 7 cdt change 01/02/2020 8 cdt delete 01/03/2020 Select * from table1 exist where (Select access, date from table1 group by access, date having trans <> 'delete') I'm looking for this result: group without a last delete row 4 btt add 01/01/2020 5 btt change 01/02/2020 In my other sql attempts, I'm only able to get the Delete row [/INST]Try this: DECLARE @t Table ( [key] int, [access] varchar(20), [trans] varchar(20), [date] datetime ); INSERT INTO @t VALUES (1, 'adt', 'add', '01/01/2020'), (2, 'adt', 'change', '01/02/2020'), (3, 'adt', 'delete', '01/03/2020'), (4, 'btt', 'add', '01/01/2020'), (5, 'btt', 'change', '01/02/2020'), (6, 'cdt', 'add', '01/01/2020'), (7, 'cdt', 'change', '01/02/2020'), (8, 'cdt', 'delete', '01/03/2020'); SELECT * FROM @t WHERE [access] NOT IN (SELECT [access] FROM @t WHERE [trans] = 'delete');</s>
<s>[INST]SQL Server licensing where SQL Server services are disabled I've used the Microsoft MAP Toolkit to discover the SQL Server installations and SQL licensable components across the estate. The toolkit has reported on a number of servers where the SQL related services are no longer running and disabled. Are there any licensing implications still having SQL installed on the servers but effectively turned off? Would Microsoft expect these servers to be licensed when it comes to true-up? [/INST]Every installed software must be licensed, at least because you (or another one) can enabled & start SQL Server. If SQL Server is disabled ans so not used, then uninstall it to be on the safe side.</s>
<s>[INST]Join Two Tables with get value AsssetCode from Max Date I'm trying join Two tables: KDSCMSCNTRCTD ----------------- CNTRCTDID | CNTRCTDCOMP | CNTRCTDLNUM | -------------------------------------- 3221 | NAV | 207 -------------------------------------- KDSCMSCNTRCTDHIST ---------------------------------------------- CNTRCTDHISTID | CNTRCTDHISTSDATE | CNTRCTDHISTCOMP | CNTRCTDHISTLNUM | CNTRCTDHISTASSCODE | ------------------------------------------------------------------------------------------ 65 | 17-NOV-21 | NAV | 207 | 00091 ------------------------------------------------------------------------------------------ 66 | 20-NOV-21 | NAV | 207 | 123 ------------------------------------------------------------------------------------------ i need only get AssetCode from (max) CNTRCTDHISTSDATE from KDSCMSCNTRCTD Like this: CNTRCTDID | CNTRCTDCOMP | CNTRCTDLNUM | CNTRCTDHISTASSCODE | ----------------------------------------------------------- 3221 | NAV | 207 | 123 ----------------------------------------------------------- select CNTRCTDLNUM as PRODID, CNTRCTDHISTASSCODE as ASSET from KDSCMSCNTRCTD left join KDSCMSCNTRCTDHIST ON CNTRCTDHISTLNUM = CNTRCTDLNUM where CNTRCTDLNUM = :CONTRACTCODE and CNTRCTDCOMP = :Company ; [/INST]Try a compact query too: select *, CNTRCTDHISTASSCODE = (select top(1) CNTRCTDHISTASSCODE from KDSCMSCNTRCTDHIST where CNTRCTDCOMP = t.CNTRCTDCOMP and CNTRCTDHISTLNUM = t.CNTRCTDLNUM order by CNTRCTDHISTSDATE desc) from KDSCMSCNTRCTD t where CNTRCTDLNUM = :CONTRACTCODE and CNTRCTDCOMP = :Company</s>
<s>[INST]Why would I not get the Select Instance screen? Trying to do an in-place upgrade from SQL Express 2014 - to SQL Express 2019 on tiny database we use for our magnetic door lock software. In the Data Migration Assistant, I have no issue identifying the Instance and running an assessment on it, but when I actually go to upgrade the DB, I never get the screen to select the instance I swear I have scoured the interwebs for this and can find no explanation or even that anyone else has even experienced this issue.[/INST]Microsoft SQL Server 2014 (SP3-GDR) (KB4583463) - 12.0.6164.21 (Intel X86) There we have it. You have a 32-bit instance. SQL 2014 was the last version to support 32-bit, so you cannot do an in-place upgrade. You will need to uninstall and reinstall.</s>
<s>[INST]How to use another way instead of while loop to pass value ? I working on sql server 2012 I need to use another way instead of using while loop to pass value to another stored procedure i have data input on table Extractreports.dbo.PartGeneration then i pass ZProductID to \[dbo\].\[SP_TradeCodeGenerateByProductAndCodeType\] to get data partial by zproductid because if i run \[dbo\].\[SP_TradeCodeGenerateByProductAndCodeType\] alone take 6 hours so are there are any way instead of while loop to pass value to \[dbo\].\[SP_TradeCodeGenerateByProductAndCodeType\] my code as below : create Proc [Parts].[sp_TradeCodeGenerateByPLandCodeType] AS BEGIN IF OBJECT_ID('Extractreports.dbo.PartGeneration') IS NOT NULL DROP TABLE Extractreports.dbo.PartGeneration CREATE TABLE Extractreports.dbo.PartGeneration ( ID INT IDENTITY(1, 1) , ZProductID INT , Proceed INT, [Status] VARCHAR(200) ) insert into Extractreports.dbo.PartGeneration ( ZProductID ) Select 4125 union all select 4123 union all select 45911 DECLARE @ZProductID INT =NULL While (Select Count(1) From Extractreports.dbo.PartGeneration where Proceed =0 AND [Status] IS NULL ) > 0 BEGIN BEGIN TRY SELECT TOP 1 @ZProductID = ZProductID FROM Extractreports.dbo.PartGeneration WHERE [Status] IS NULL AND Proceed=0 EXEC [dbo].[SP_TradeCodeGenerateByProductAndCodeType] @ZProductID UPDATE Extractreports.dbo.PartGeneration Set Proceed = 1,Status='Done' Where @ZProductID=ZProductID END TRY BEGIN CATCH UPDATE Extractreports.dbo.PartGeneration Set Proceed = 1,Status= CONCAT('Failied:',ERROR_MESSAGE()) Where @ZProductID=ZProductID END CATCH END ALTER PROC [dbo].[SP_TradeCodeGenerateByProductAndCodeType] ( @productID INT ) AS BEGIN select * from trades where zplid=@productID select * from codesData where zplid=@productID end [/INST], Loops are rarely used, and queries do most of the job. Still, sometimes, loops prove to be very useful and can ease our life a lot You shouldn’t use loops for anything you like. They could cause serious performance issues. You can execute the loop separately, and if the performance is not bad, then insert the loop result into a temporary table. Then, as Erland said, rewrite the process to accept table-valued parameters.</s>
<s>[INST]Windowed functions cannot be used in the context of another windowed function or aggregate. i am trying to sum of Column then below error is coming. with cte as( SELECT C.ContNo, --C.Rag_Type, case when cat.Cat_name='Savers' then 'A' else r.R_type_name END Rag_Type, C.entrydate as EntryDate, C.ConWeight as Act_weight, C.No_Of_Bales as Act_Qty,iSNULL(Sum(I.R_Weight),0)Isu_Weight,iSNULL(Sum(i.R_QTY),0)Isu_QTY,(C.ConWeight-iSNULL(Sum(I.R_Weight),0)) as Pending_Weight, (C.No_Of_Bales-iSNULL(Sum(i.R_QTY),0)) as Pending_Qty FROM Containerno C inner join ConCatagory cat on cat.Cat_ID=c.Cat_ID inner join tbl_ContD CD on CD.CID=C.CID left join tbl_Issuance_Rags I on I.D_ID=CD.D_ID left join tbl_Range as r on (c.con_value >= r.R_Value_From AND C.con_value <= r.R_Value_to) where C.delid is null and I.Delid is null and C.entrydate>'2020-12-31' and c.con_status is null group by C.ContNo,C.Contrackno, C.ConWeight,C.No_Of_Bales,C.entrydate,cat.Cat_name,r.R_type_name ), cte2 as( select Rag_Type Type ,sum(Pending_Weight) Weight from cte where Pending_Qty>0 and EntryDate>'2020-12-31' group by Rag_Type) select Type,Weight, ISNULL(cast((Weight)*100.0/(sum(Weight)over(PARTITION BY (1) ))AS numeric(10,2)),0) as Per from cte2 group by Type,Weight union all Select 'Total', sum(isnull(cast(Weight as float),0)),sum(ISNULL(cast((Weight)*100.0/(sum(Weight)over(PARTITION BY (1) ))AS numeric(10,2)),0)) from cte2 group by Weight [/INST]Please try: with cte as( SELECT C.ContNo, --C.Rag_Type, case when cat.Cat_name='Savers' then 'A' else r.R_type_name END Rag_Type, C.entrydate as EntryDate, C.ConWeight as Act_weight, C.No_Of_Bales as Act_Qty ,iSNULL(Sum(I.R_Weight),0)Isu_Weight ,iSNULL(Sum(i.R_QTY),0)Isu_QTY,(C.ConWeight-iSNULL(Sum(I.R_Weight),0)) as Pending_Weight, (C.No_Of_Bales-iSNULL(Sum(i.R_QTY),0)) as Pending_Qty FROM Containerno C inner join ConCatagory cat on cat.Cat_ID=c.Cat_ID inner join tbl_ContD CD on CD.CID=C.CID left join tbl_Issuance_Rags I on I.D_ID=CD.D_ID left join tbl_Range as r on (c.con_value >= r.R_Value_From AND C.con_value <= r.R_Value_to) where C.delid is null and I.Delid is null and C.entrydate>'2020-12-31' and c.con_status is null group by C.ContNo,C.Contrackno, C.ConWeight,C.No_Of_Bales,C.entrydate,cat.Cat_name,r.R_type_name ), cte2 as( select Rag_Type Type ,sum(Pending_Weight) Weight from cte where Pending_Qty>0 and EntryDate>'2020-12-31' group by Rag_Type) select Type,Weight, ISNULL(cast((Weight)*100.0/(sum(Weight)over(PARTITION BY (1) ))AS numeric(10,2)),0) as Per from cte2 group by Type,Weight union all Select 'Total', sum(isnull(cast(Weight as float),0)) ,sum(cc) from (select *,ISNULL(cast((Weight)*100.0/(sum(Weight)over(PARTITION BY (1) ))AS numeric(10,2)),0) cc from cte2) c2 --group by Weight If this does not solve your problem, please share us your table structure (CREATE TABLE …) and some sample data(INSERT INTO …).</s>
<s>[INST]Bulk Insert Operation Logging Good Morning, For Bulk Insert operation, does SQL Server log every individual row in FULL recovery model?[/INST]Good afternoon. :-) The answer to your question is, yes it does.</s>
<s>[INST]SQL server cluster error I Have two SQL server (one of the server on live subnet ) and another SQL server in DR subnet ) When try to add the listener IP address it gives me the error number: 19456 [/INST]When try to add the listener IP address it gives me the error number: 19456 Error 19456: >None of the IP addresses configured for the availability group listener can be hosted by the server '%.*ls'. Either configure a public cluster network on which one of the specified IP addresses can be hosted, or add another listener IP address which can be hosted on a public cluster network for this server. It's pretty straight forward. It's giving you the server for which you didn't specify an IP address in the listener configuration that the server given could bind to an interface. Basically you're missing an IP in another subnet, the one which that server exists. Get another IP from the subnet which that server can bind to a cluster interface and add it to the listener.</s>
<s>[INST]Why MS SQL does not have MAX function between multiple values? Hi all, I'm working on MS SQL and readlly need Max function between multible value ( like: greatest function in MySQL, example: Max(value1, value2, value3...), I have to use alternative solution: "select max(column) FROM (VALUES (1), (2), (3),...) )' so I have a question: Why MS SQL does not have MAX function between multiple values? Thanks, Cuong[/INST]I have some news for you! This query runs on Azure SQL Database: SELECT greatest(1, 2, 4, 5), least('Hugo', 'Laura', 'Adele', 'Oscar') It is not available in SQL 2019, but since Microsoft works with "cloud first", I would be very surprised if these functions will not appear in SQL 2022, which Microsoft recently announced. (Currently only in private preview.)</s>
<s>[INST]are there are any way to get partc without make join by Verification Hash ? I work on sql server 2014 I need to get partc as expected result Actualy i need partc from table #partsc that have Verification Hash on table #VervicationCode are there are any way to get part c without join with Verification Hash create table #partsc ( partc int, [VerificationHash] VARBINARY(512) NULL ) insert into #partsc(partc,VerificationHash) values (11234,0x566B391EDEB07A47B17B89265ABE19850655885D83247AE7E7C28849D8873A31F56D139E4987BFE85B476035E39B7308C5D203955A238F92D5A2096B50AD674C), (15431,0x5677965D16CEEDC754EAED74780662518E132F08C1B6CFF67BE62D21100C3B4C63E09937BB7153CDE67550F957AFBB23658B2193EB842FC173A8F8460DED246D), (67501,0x569132E995038072EA4AE52DC760FCB2C21AE1A6F047C66FF86B483BF575DE2EF412B3B10CDC8B8DC8B8D31D28BF90442C31811F13EC5B49DE1EBC008B6EEF16), (87190,0x56C5668A7FCB015D39EE602FAC80124050D0ADCA684D77FC99D7C293DCC09DA1A4FA2514F89E86D7619AE20A72C6CAE2A7BFE776F89C5494C36994C84241D705), (987610,0x56E0315397B4A932570101661B449FC41DF9683F5EDCC7387A8C9FA8E357A06FCF1989587CCF3E0548F79F36BB2F5C91BF6CD9E988EA9922C5C865A043B51B1F), (89871,0x57B1B8FF59BFE3F788AA1C6D5CFFC40D54F0D494D60B43CED1B52C1E290CC8AE62C3E1220365F1DCB0A00688AF92222DC32CC5454DCF9572812735D9FAF7E3C7), (12909,0x57DAFCAA14E6561FD8C2109627732DFDBEC5E169682080EF1107FA96ED505CC18BD22924BFA19A1A346BB15440FF48F53202A88672AD6FC66F4DAF0D518BC69C) create table #VervicationCode ( [VerificationHash] VARBINARY(512) NULL ) insert into #VervicationCode(VerificationHash) values (0x5677965D16CEEDC754EAED74780662518E132F08C1B6CFF67BE62D21100C3B4C63E09937BB7153CDE67550F957AFBB23658B2193EB842FC173A8F8460DED246D), (0x569132E995038072EA4AE52DC760FCB2C21AE1A6F047C66FF86B483BF575DE2EF412B3B10CDC8B8DC8B8D31D28BF90442C31811F13EC5B49DE1EBC008B6EEF16), (0x56C5668A7FCB015D39EE602FAC80124050D0ADCA684D77FC99D7C293DCC09DA1A4FA2514F89E86D7619AE20A72C6CAE2A7BFE776F89C5494C36994C84241D705), (0x56E0315397B4A932570101661B449FC41DF9683F5EDCC7387A8C9FA8E357A06FCF1989587CCF3E0548F79F36BB2F5C91BF6CD9E988EA9922C5C865A043B51B1F) expected result will be partc 15431 67501 87190 987610 [/INST]Order will not matter for the identity value generation because it is only a surrogate key you can use instead of the larger VerificationHash value. Below is an example, including DDL and revised EXISTS/IN/JOIN queries to use the id column instead of VerificationHash. --add VervicationCodeID identity column for surrogate key ALTER TABLE #VervicationCode ADD VervicationCodeID int IDENTITY NOT NULL; --add VervicationCodeID column ALTER TABLE #partsc ADD VervicationCodeID int NULL; --update partsc VervicationCodeID based on matching VerificationHash values UPDATE partsc SET VervicationCodeID = VervicationCode.VervicationCodeID FROM #partsc AS partsc JOIN #VervicationCode AS VervicationCode ON VervicationCode.VerificationHash = partsc.VerificationHash; --queries to use VervicationCodeID SELECT partc FROM #partsc WHERE VervicationCodeID IN ( SELECT VervicationCodeID FROM #VervicationCode ); SELECT partc FROM #partsc AS partsc WHERE EXISTS ( SELECT 1 FROM #VervicationCode AS VervicationCode WHERE VervicationCode.VervicationCodeID = partsc.VervicationCodeID ); SELECT partc FROM #partsc AS partsc JOIN #VervicationCode AS VervicationCode ON VervicationCode.VervicationCodeID = partsc.VervicationCodeID;</s>
<s>[INST]SQL Server and Windows on the same disk (allocation unit size 64kb-4kb) Hello, I am running a server with SQL server with 2 x 960GB NVME Datacenter SSD in RAID1, windows files and database and default database files on the same disk. This server is using the default format allocation size 4Kb. I have read that 64Kb is better for SQL and this server is only hosting SQL server. Should I reformat the server and reinstall Windows 2019 server with 64Kb allocation size ?[/INST]Dunno. Normally, you would not have databases on the system disk anyway. Well, you can have master, model and msdb on that disk - it may not be worth the hassle to move them. But tempdb and user databases should be elsewhere. At least if this a production server. It can be a lot easier to extend system disk. And, yes, there is the thing about the block size. I'm not a Windows expert, but my gut feeling is that 64KB is not a good block size for the OS, if it produces a lot of small temp files.</s>
<s>[INST]SQL Server 2014 upgrade and updates instalation Hello, I am going to perform an in-place upgrade of a SQL Server 2014 to 2017 cluster. The cluster has 3 nodes. After i have upgraded one node to SQL 2017 can i immediately install latest cumulative update on that node or do i have to failover to the first upgraded node and then install all cumulative updates? Thanks, Jramalho [/INST]You can install the CU direct after migration.</s>
<s>[INST]Msg 8114, Level 16, State 5, Line 1 Error converting data type nvarchar to numeric. I have column datatype in nvarchar(50) ,now i want to convert it into decimal(10,2) ,it is giving error Msg 8114, Level 16, State 5, Line 1 Error converting data type nvarchar to numeric. ALTER TABLE containerno ALTER COLUMN Cl_amt decimal(10,4); [/INST]Error converting data type nvarchar to numeric. A clear error message, your varchar data contains in some rows not convertable/numeric values. You can try finding them with select * from containerno where isnumeric(Cl_amt) = 0 But no garantuee it will find all cases, e.g. exponential presentation of floats like 10E2 are numerics to, but not implicit convertable to numeric data type, only to float.</s>
<s>[INST]Always On without read only replica Hello, If I set up this kind of configuration, does it serve the purpose of HA ? I have 2 node WSFC, no shared storage. I have installed SQL 2017 Enterprise on each node. Node 1 - Primary Server - Read Write. Node 2 - Secondary Replica - No Read Synchronous Commit, Automatic Failover. [/INST]If I set up this kind of configuration, does it serve the purpose of HA ? and > Synchronous Commit, Automatic Failover. Yes, it serves the purpose. Whether or not the cluster can maintain quorum in the event of a node loss is another story. Make sure there is a cluster witness resource.</s>
<s>[INST]mylittleadmin user and permission issue Hi, I have created a SQL database in plesk panel along with a user. I am able to login to sql query analyzer 2000 through that user but unable to select any table. It says user does not have permission to perform this action. Can anyone pls guide me. Thanks Juzer [/INST]I deleted the DB. Created one fresh with new user mainDR2. > I logged into sql query analyzer with mainDR2 > I wrote following > 1. Use MyDatabase > user main is coming from old database when i import in Plesk. > I am sure i am missing something silly > Even Select * into Member from main.Member works properly I don't know if you have any experience with later versions of SQL Server, but if you have, SQL 2000 can certainly be confusing. If you are logged as the user main and you say CREATE TABLE Member That table will be created in your default schema. Actually, this is true for all versions of SQL Server. But what is weird in SQL 2000 and earlier version is that your default schema is always your username and this cannot be changed. Or more specifically: on SQL 2000 owner and schema was the same, and we never talked about schema in those days. Best advice: stay away from SQL 2000.</s>
<s>[INST]Is SQL Express 2013 SP3 extended support till 2026 paid or free? Is SQL Express 2013 SP3 extended support till 2026 paid or free?[/INST]During Extended Support period Microsoft may provide free security updates, for everything else you have to pay.</s>
<s>[INST]Need to help to figure out the lag time. I have to figure the lag time to the 2 rows below. Business rule is showing below. I am using SQL 2017. Thank you so much in advance. -- Return the latest date. IF OBJECT_ID('Tempdb.dbo.#Temp', 'u') IS NOT NULL DROP TABLE #Temp GO CREATE TABLE #Temp ( DBName VARCHAR(20) NULL, IsPrimaryOrReplica VARCHAR(25) NULL, synchronization_state_desc VARCHAR(30) NULL, last_commit_lsn VARCHAR(40) NULL, last_commit_time DATETIME NULL ) GO INSERT INTO dbo.#Temp(\[DBName\],\[IsPrimaryOrReplica\],\[synchronization_state_desc\],\[last_commit_lsn\],\[last_commit_time\]) VALUES ('MyProd', 'Primary', 'SYNCHRONIZED', 11670080000015441600026, '2021-12-03 11:10:02.467') INSERT INTO dbo.#Temp(\[DBName\],\[IsPrimaryOrReplica\],\[synchronization_state_desc\],\[last_commit_lsn\],\[last_commit_time\]) VALUES ('MyProd', 'Secondary', 'SYNCHRONIZING', 11670080000015425600005, '2021-12-03 11:10:08.467') SELECT \* FROM dbo.#Temp; GO -- Business Rule. -- Take the last commit time of primary - secondary and return the lag time. In this case, it should return 6 sec. DBName IsPrimaryOrReplica synchronization_state_desc last_commit_lsn last_commit_time Lag_time ------------------------------------------------------------------------ MyProd Primary SYNCHRONIZED 11670080000015441600026 2021-12-03 11:10:02.467 MyProd Secondary SYNCHRONIZING 11670080000015425600005 2021-12-03 11:10:08.467 6 sec SELECT \* ,DATEDIFF(ss, last_commit_time '??? specify seondary', last_commit_time 'specify primary') AS \[Lag_time\] FROM dbo.#Temp; GO Result want; DBName IsPrimaryOrReplica synchronization_state_desc last_commit_lsn last_commit_time Lag_time ------------------------------------------------------------------------ MyProd Primary SYNCHRONIZED 11670080000015441600026 2021-12-03 11:10:02.467 MyProd Secondary SYNCHRONIZING 11670080000015425600005 2021-12-03 11:10:08.467 6 sec [/INST]Try something like this: select *, case when IsPrimaryOrReplica = 'Secondary' and synchronization_state_desc = 'SYNCHRONIZING' then datediff( second, (select max(last_commit_time) from #Temp where DBName=t.DBName and IsPrimaryOrReplica='Primary' and synchronization_state_desc='SYNCHRONIZED' and last_commit_time < t.last_commit_time), last_commit_time) else null end [Lag (seconds)] from #Temp t Adjust it according to your needs.</s>
<s>[INST]Buffer cache and plan cache If I m execute a query for first time which is taking 10 seconds and its fetching 100 GB of data , SQL Server need to fetch from disk the pages and put into buffer cache before come out with results. My question is what will happen, if I m cancelling the query while its executing query within 5 seconds, so I believe few pages might be already in buffer cache ,do SQL Server will flush out the pages and plan which its already in the buffer cache and plan cache or it will remain there in cache although I have cancel the query[/INST]do SQL Server will flush out the pages and plan which its already in the buffer cache and plan cache or it will remain there in cache although I have cancel the query Pages will remain in the buffer cache even if the query is cancelled. These will be reused when the query is rerun (assuming they are still in cache) or by other queries needing the same pages.</s>
<s>[INST]How to find All user ids who use my test database and to terminate their running jobs? Hello, I would like to get your help and expertise on how to find all user id who use the database because I want to terminate their jobs after after certain time at night, let's say 10pm at night when I want to users using the database because I have a batch job running at 10pm and I want to use the computer resources for the batch job. I googled and I found the following sql statements for terminating all session id that use my AdventureWorksDw2019 database use master DECLARE @kill varchar(8000) = ''; SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';' FROM sys.dm_exec_sessions WHERE database_id = db_id('AdventureWorksDW2019') I would like to know the user ids of all of the session ids that I terminate above. Do you know if there is a table that links with this sys.dm_exec_sessions that may give me all of the user ids ? I hope that my question makes sense. If it is not, may you please propose a way that could accomplish the same goal? Many Thanks for the help, Du [/INST]Not sure what your question really is. The name of the login is in the column sys.dm_exec_sessions.login_name. But a more direct way is to run ALTER DATABASE yourdb SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE This will kick out all non-admin users. You need this command at the end of the job: ALTER DATABASE yourdb SET MULTI_USER Then again, as Tom suggests, this nothing you do normally. Least of all because you "want to use the computer resources for the batch job." But some applications have nightly batches where bad things could happen if users area active in the system when the nightly batch runs. But this is something you typically solve in the application, one way or another.</s>
<s>[INST]Some Chinese characters not found by query Hi all, first time posting so please forgive i have missed some important info. I have tried searching for some similar thread but couldn`t find one. I have an app that is React-Java-MsSql and the problem that i am facing is that some Chinese characters produce a result when used for searching, through the ui, and some don`t. For example if i use 啊 i will get the expected result 㐀啊〾⿻䲢䴘䶮⺁ but if i try using 㐀 i get noting. If i execute a query in management studio i get the same results, 啊 produces a hit and 㐀 doesn`t. Data is stored correctly in the db, i can see that in management studio and the request does contain the correct characters each time. Field in the db table is nvarchar and the current collation is SQL_Latin1_General_CP1_CI_AS. I`m using sql server 2019 ver.15.0.2000.5. I have tried changing collation on that field, tried some more specific collations. For example if i set the collation on Chinese_Traditional_Stroke_Count_100_CI_AI and execute a query in the management studio i get a result on 㐀 but no results on 啊, and in the ui i get a result on 啊〾 but not on 啊 or 㐀. Am i missing something or is this expected behaviour? It is a multi language app and needs to cover different languages and characters, Latin1_General works fine for the most part covering different languages but in this specific case some Chinese characters are not working. Is this the price of wanting to cover different languages? Its not as if Chinese language is not working at all just some characters. My main question is is there a way to cover more Chinese characters with some 'general' collation? Any help is welcome or if there is an existing thread that i have missed please direct me to it. Thanks Nikola [/INST]Both next queries seem to work: declare @tab table ( txt nvarchar(max) collate SQL_Latin1_General_CP1_CI_AS ) insert @tab values ( N'㐀啊〾⿻䲢䴘䶮⺁' ) select * from @tab where txt like N'%啊%' select * from @tab where txt like N'%㐀%' Is it possible to reproduce the problem in Management Studio?</s>
<s>[INST]How to generate unique strictly ascending numbers without locking penalty Dear colleagues, I know this is an old, old question. The problem is, I do not have a good solution and cannot find anything useful online. I have a table with journal entries. The accountant wants the journal entries to have a strictly ascending number ordered on moment of generation. What I did is making a table with a single record containing the last used number and placing a table lock on this table whenever a journal entry is needed. The idea was that every process that needs to generate a journal entry starts with locking this table. I know this is a performance killer whenever you have long running transactions generating journal entries. But what is worse, in time some processes have been created that do generate journal entries but that do not start with locking my single record table. Result: deadlocks. If gaps would have been allowed, I could have used a sequence or an identity field. If a strictly ascending number is necessary, but the moment of generation isn't relevant, I could put generated journal entries in a queue after the transaction commit, letting an async process generate the numbers, or something along these lines. Using something like this will prevent rolled back transactions creating gaps in the order. Does anyone have an idea how to have strictly ascending numbers without the drawback of locks / deadlocks?[/INST]There is not a built in way to create a sequence/identity without the opportunity of gaps. The simplest answer to your question, without gaps, is to use an IDENITITY column and then use ROW_NUMBER() order by the identity column. That will give you a sequence without gaps. However, that is very costly to do every time. The only other way is to create your own sequence table. Then the table would rollback. However, if you are in a high transaction count, that will cause blocking waiting for the numbers. This is why identity/sequences cache and allow for gaps.</s>
<s>[INST]Auto RTRIM and LTRIM on query result ? Hello, I'm working on SQL server 2016. Is there a specific syntax to have any queries returning data without any space before and after strings ? I do not speak about how to store data, i do not need to change anything but the query returning. For example i have a table with a column CHAR(40) and when i run a query (SELECT *) on it, i have all spaces after the string : 'TEST ' I need a command to run on SQL server to make any queries return : 'TEST' Is anyone can help ? Best regards[/INST]1. You are using a column with **CHAR(40)** data type. It means there are always 40 characters with trailing spaces regardless of the stored value. 2. Just modify that column as **VARCHAR(40)** data type. This way spaces are not allocated, not stored, and no need to TRIM() the value.</s>
<s>[INST]Extract a pattern of numbers out of a varchar(max) column we have a table which has a column, and we need to extract only the value that matches the pattern of numbers defined as ####-#### where # is any digit from 0-9 and it's only eight digits with a hyphen in the middle, four digits on each side of the hyphen and white space each side of the value to extract. What is the best method to extract the ####-#### values out of the column? Declare @T Table (ID int, DescItem varchar(max)) Insert into @T(Id, DescItem) Values (10,'this is just some text here, and we need to pull out 1200-7741 data pertaining to an id code'), (20,'Another line 1402-8704 item with additional information'), (30,'And More information still 1600-7774') Select * from @T The values to extract out of each record in the above scenario are: 1200-7741 1402-8704 1600-7774 and they can be anywhere in the text, and of course, the numbers themselves can and will be different. thank you [/INST]; WITH get_startpoint AS ( select ID, DescItem, start_point = patindex('%[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]%', DescItem) from @T ) SELECT ID, Number = CASE WHEN start_point > 0 THEN substring(DescItem, start_point, 9) END</s>
<s>[INST]Get X amount of records and truncate table then re-insert Hi I have a single table with 2 million rows. I need only a thousand of them and i can get them easily by doing a where clause such as SELECT FROM MYTABLE WHERE (IsBroken = 0) I tried deleting the records using where IsBroken = 1 and 'Delete from' but this was writing to the Transaction log and that got full quickly. Is there a way that i could get all the required records store them temporarily and then truncate the table and re-insert the temporary records i require? [/INST]You can delete them in batches to prevent the transaction log from getting too full. DECLARE @rowcnt INT = 1; WHILE @rowcnt > 0 BEGIN DELETE TOP (1000) FROM MYTABLE WHERE (IsBroken = 0) SET @rowcnt = @@ROWCOUNT;</s>
<s>[INST]Is it possible to write a pivot query where you have units and dollar amount from an ERP system for the past few years I was thinking for the pivot query how you define the columns then the rows are the group you are looking for. For example, columns in a sales report might be the years, and the row details are the accounts. Is it possible to make it that a column has units and $ amount? I was thinking something like '2020 Qty', '2020 $', '2021 Qty', '2021 $'[/INST]As long as you stay away from the PIVOT keyword, about anything is possible. A pivot query is best written the appropriate aggregate function and CASE. The above might be: SELECT Account, SUM(CASE WHEN year = '2020' THEN Qty END) AS "2020 Qty", SUM(CASE WHEN year = '2020' THEN Amount END) AS "2020 $", SUM(CASE WHEN year = '2021' THEN Qty END) AS "2021 Qty", SUM(CASE WHEN year = '2021' THEN Amount END) AS "2021 $" FROM tbl</s>
<s>[INST]Move SQL 2014 Server to a new machine but lost SN HI I would like Move SQL 2014 Server to a new machine,but cant' find S/N and invoice. How can I export authorization to other server?[/INST]There is nothing to "export", you have the licenses only on paper and you should better find them or ask the seller for a copy. If you mean the product key (which is not the license) for the installation, you can query it with Declare @Val nvarchar(4000) Exec master .dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\Setup', N'ProductCode', @Val output Select @Val As ProductCode</s>
<s>[INST]SQL Server Query Optimizer estimates ~1 row, but eq_rows statistics shows ~12000 I have a (composite) index consisting of columns A, B, C and D. The statics are up to date and show EQ_ROWS value 12000 for value 'x' (that is the RANGE_HI_KEY) for column A. When I do a SELECT * FROM <table> WHERE a = 'x' the Estimated Query Plan shows for all operators (index seek on the mentioned composite index, key lookup and nested loop) an estimated number of rows of ~1. How is this possible? I would have thought it to be 12000 for the index seek for example. Note that in reality my column names have decent names, but for company security reason I cannot use real names. I hope my explanation is clear enough.[/INST]I am afraid that I don't have a good answer for you. I know that there are imperfections in Showplan and sometimes information does not display fully accurately. In this case, I notice that there are a few more filter conditions on the DISPENSEEVENT table than just the CLIENTID. The remain predicates are filtered in the Key Lookup, which is just below the Index Seek. It is possible that the total estimate for the predicates is 1 row. In any case, it seems to be that there is all reason to consider adding an index on (CLIENTID, MDEMEDICALGUIDANCESTATEID, DISPENSEEVENTPROCESSORIGINID, PARENTDISPENSEEVENTID, MDEAPPROVALSTATEID) INCLUDE (STATE). I need to add the caveat that I only see this query, and I don't know how dynamic these conditions are. That is, if this query exists in multiple permutations, it may not be wise to add indexes for all of them.</s>
<s>[INST]SQL Server Express 2019 with Visual Studio 2019 I have a project with a SQL database that is deployed on a Server running SQL Server Express 2015. I now have a new server and I am trying to open the existing project in Visual Studio 2019 Community and deploy on the new Server via SQL Server Express 2019. Whilst I have successfully attached the SQL Database to the new server under SQL Sever Express 2019, I cannot access this via Visual Studio Community 2019 running on a PC. Visual Studio says the database cannot be opened because it is version 904. The server supports version 852 and earlier. I have tried reinstalling with just SQL Server Express 2019 but the same message. How do I work with a 2019 database on VS ?[/INST]Visual Studio mainly has my head spinning, but I think the issue is that VS wants to use localdb, and is picking up an older version of SQL Server. I think that VS 2019 comes with SQL 2017 and not SQL 2019. (Because VS 2019 was released before SQL 2019 went RTM.) Open a command-line window and run sqllocaldb info sqllocaldb version to see which instances versions of sqllocaldb you have installed. If you say sqllocaldb info instance You get more detailed info on that instance, including version. I think Express installs sqllocaldb automatically. You could delete the instance that VS uses and create a new one based on SQL 2019. Use the help option with sqllocaldb to see the commands for this.</s>
<s>[INST]Single User Mode taking over 36 hours Hello: After receiving an error message sayin theie may be corruption in the database I decided to do a repair. I ran the script with: ALTER DATABASE PRODUCTION SET SINGLE_USER; GO Started on Saturday morning and here is it on Sunday afternoon and here it is on Sunday afternoon and it is still "Executing query". I'm assumiong if I stop the query now it will be a disaster. The .mdf file is around 11gb in size. The error that caused me to start thei process was error 824. I planned on running DBB CHECKDB after I put into single user mode. TIA[/INST]If that is all you say, the command will wait until there are no processes running in the database. You will either have to chase around manually to kill them, and this is what you want to do, if you are anxious that you may will something important. Or you can be a little more brutal: ALTER DATABASE Production SET SINGLE_USER WITH ROLLBACK_IMMEDIATE This will kill all processes that has this DB as its current database, and usually returns within a couple of seconds. However, if a process is running code outside the SQL Server instance, for instance on a linked server, it will not notice that has been asked to exit. You can cancel the command you have running. There will be no damage done. When it comes to the corruption, keep in mind that corruption does not come out of the blue, but it often due to hardware issues or issues in the I/O subsystem. Unless you know there has been some special event that may have caused this, you should consider the current setup as tainted.</s>
<s>[INST]Database Corruption Hello: We have a manufacturing application connecting to a SQL Database and endusers are experiencing errors in a specific part of the app. There are several differnt modules, financial, shipping, partnumbers and others. Only the part numbers seem to be affected. The SQL server event logs are showing error 824 ...error that threatens database integrity .... When I run CHECKDB against the database I get: Msg 8909, Level 16, State 1, Line 1 Table error: Object ID 0, index ID -1, partition ID 0, alloc unit ID 0 (type Unknown), page ID (1:700540) contains an incorrect page ID in its page header. The PageId in the page header = (0:0). Msg 8909, Level 16, State 1, Line 1 Table error: Object ID 0, index ID -1, partition ID 0, alloc unit ID 0 (type Unknown), page ID (1:700541) contains an incorrect page ID in its page header. The PageId in the page header = (0:0). CHECKDB found 0 allocation errors and 2 consistency errors not associated with any single object. Msg 8939, Level 16, State 98, Line 1 Table error: Object ID 156579646, index ID 0, partition ID 10261603680256, alloc unit ID 10261603680256 (type In-row data), page (1:700539). Test (IS_OFF (BUF_IOERR, pBUF->bstat)) failed. Values are 133129 and -1. Msg 8928, Level 16, State 1, Line 1 Object ID 156579646, index ID 0, partition ID 10261603680256, alloc unit ID 10261603680256 (type In-row data): Page (1:700539) could not be processed. See other errors for details. Msg 8928, Level 16, State 1, Line 1 Object ID 156579646, index ID 0, partition ID 10261603680256, alloc unit ID 10261603680256 (type In-row data): Page (1:700540) could not be processed. See other errors for details. Msg 8928, Level 16, State 1, Line 1 Object ID 156579646, index ID 0, partition ID 10261603680256, alloc unit ID 10261603680256 (type In-row data): Page (1:700541) could not be processed. See other errors for details. CHECKDB found 0 allocation errors and 4 consistency errors in table 'Change_History' (object ID 156579646). CHECKDB found 0 allocation errors and 6 consistency errors in database 'PRODUCTION'. repair_allow_data_loss is the minimum repair level for the errors found by DBCC CHECKDB (PRODUCTION). It was most likely caused by a file level restore after a ransomware attack and was advised to to a repair REPAIR_ALLOW_DATA_LOSS on a new copy of the database. Since I am a novice SQL admin and have very limited knowledge, what wpould be my next plan of action? What would be the likelyhood that only the part that they are having errors on would experience? TIA[/INST]This kind of corruption is always due to physical hard drive problems. Having the time 12 hours different did not cause this issue. You need to investigate the hard drives. As for fixing the issue, you need to restore a good backup and reenter whatever you can. If you recover with data loss, it is very difficult to know what has been lost. The errors my go away, but you will not really know what is missing.</s>
<s>[INST]Can a cursor be create from a stored procedure I have the following in a stored procedure: DECLARE myCursor CURSOR READ_ONLY FOR exec rpt1099R_sp @payrollYear = @curYear -1 When executing to create the procedure I get the error: Msg 156, Level 15, State 1, Procedure zeroExclusion_sp, Line 15 [Batch Start Line 0] Incorrect syntax near the keyword 'exec'. Can I create a cursor from a stored procedure? If so, how? [/INST]that is not possible. FOR in a cursor declaration must be followed by a SELECT statement. Explain what you really want to do and we may be able to help you.</s>
<s>[INST]Is user mapping required for database login in MS SQL Server 2019? Hi! After importing a database backup from MS SQL Server 2012 into MS SQL Server 2019 I quickly found out I was not able to login into it anymore. In SSMS there is an appropriate entry (an AD user group) under Databases -> [database name] -> Security -> Users, and up till now this sufficed to be able to login. However, it now seems necessary to also add an entry to Security -> Logins, and then map this entity to the database user. Anyway, that was the only way I could make it work. So, I'm wondering: 1. Is user mapping in MS SQL Server 2019 a requirement to be able to login into a database? (It was not in versions 2008 and 2012.) 2. Or is there another way to login just as a database user? 3. If the answer to question 1 is yes, then what is the use of being able to add a database user / group from a domain? Thank you for your time![/INST]has already answered the important points. I just like to cover the last question: > If the answer to question 1 is yes, then what is the use of being able to add a database user / group from a domain? Keep in mind that a user can have access to the instance from one or more AD groups. But then the user or an AD group may need specific permissions in a database, and therefore you may need to add the user on this level, although the user has no login of its own.</s>
<s>[INST]Cannot connect to SQL Server Express I have a Server running Windows Server 2019 Essentials and SQL Server Express 2019. This can be accessed on the machine through SSMS. I have followed the configure the SQL Server remote access ( Enable TCP/IP Port 1433, restarted services, Added rules in Firewall) but the Server is not showing Under network servers via SSMS on a network pc. I have uninstalled and reinstalled SQL Server a number of times and followed the setup but no effect. What am I likely to be missing ? How can I solve ?[/INST]For integrated security to work in a workgroup, you must have the same username and password on both machines. But it may still not work, as some setting in Windows has to be in the appropriate position. You are better off using SQL authentication. That is, you login with a user and password defined in SQL Server. You need to configure the instance to permit SQL authentication. Right-client the server node itself and select Properties, and then go the Security page. You need to restart SQL Server for the change to take effect. You create a login like this: CREATE LOGIN Ian WITH PASSWORD = 'IWillNotTellYou!' Presumably, you want to be sysadmin: ALTER SERVER ROLE sysadmin ADD MEMBER</s>
<s>[INST]Proper way to delete a SQL Server Database Hi, I have a SQL Server Database named 'ToBeDeleted' that I would like to delete permanently. Can anyone here tell me if executing the following script would be an appropriate way to do this? .... USE master GO DROP DATABASE ToBeDeleted GO Thank you in advance, Paul [/INST]Yes that will drop the database in most cases. The one situation it will not is when there are active processes in the database. In this case you will get an error. If this occurs, you can run this brutal command: ALTER DATABASE ToBeDeleted SET SINGLE_USER WITH ROLLBACK IMMEDIATE Now DROP DATABASE should succeed.</s>
<s>[INST]Proper way to duplicate a database Hi, I have a SQL Server Database that is used by the company I work for. I'll call this one 'ProductionDatabase'. I'd like to create a duplicate copy of 'ProductionDatabase' called 'TestDatabase' that I can use for my own purposes. (I'm going to try to develop a new front end application, but I do not want to risk compromising the company's real data). It is not clear to me how to do this. I did a Full Backup of ProductionDatabase that I saved to disk as a .bak file. Now I am trying to figure out how to restore this backup to a differently named database (TestDatabase). In the 'Restore Database' utility in SSMS, I couldn't find a way to restore a backup to a database name that doesn't exist. This led to me creating a new (empty) database named 'TestDatabase'. I then went back into the Restore Database utility and tried to restore from the .bak file to the newly created 'TestDatabase'. When I tried this, I got the following error message: "Restore of database 'TestDatabase' failed. However, the Tail-log backup operation completed successfully." If anyone here can tell how I can accomplish this task, I would greatly appreciate it. Thanks in advance, Paul [/INST]This is the command: RESTORE DATABASE TestDatabase FROM DISK = 'C:\temp\MyBackup.bak' WITH MOVE 'ProductionDatabase' TO '<somepath>\TestDatabase.mdf'. MOVE 'ProductionDatabase_log' TO '<somepath>\TestDatabase.ldf' Some notes: The name that follow `DISK =` is the path to the backup file. Replace with the actual backup. The names that follow MOVE are the logical names of the files, and must agree with those in the backup. You can find them with this command: RESTORE FILELISTONLY FROM DISK = 'C:\temp\Backup.bak' The logical names are in the first column. The names that follow TO are the file locations for the files of the new database. They can be anywhere, but you should make a judicious choice. Presumably they should be in the same path as other database. (You can find the locations of the files for an existing database with sp_helpdb.) If you created an empty database called TestDatabase, drop it first. RESTORE will create a new database. If you keep the empty database, you will get an error as SQL Server thinks you may lose data if it would just wipe away the files for the existing database. As for the dialogues in SSMS, I can't help much there since I never use them. But I recall that they are more confusing than helpful.</s>
<s>[INST]SQL Server Database stuck in 'Restoring' state Hi, I posted a question about an hour ago about how to create a duplicate copy of a database. It appears now that my initial attempt at doing this has had an adverse side effect. What I did is the following: (1) I used the SSMS interface (as opposed to SQL script) to back up my database named 'ProductionDatabase' to a .bak file (2) I created a new database named 'TestDatabase' (3) Using the SSMS interface, I attempted to restore 'TestDatabase' from the .bak file. When I tried this, I got the following error message: "Restore of database 'TestDatabase' failed. However, the Tail-log backup operation completed successfully." Not only did my backup not get restored / copied to TestDatabase, but now the status of 'ProductionDatabase' shows as "Restoring". In this state, the front end client application we use is not able to connect to it. If anyone can suggest how I might be able to solve this issue, I would greatly appreciate it. I'd still like to know the proper way to duplicate a database (as I asked in my previous post), but this issue is now a higher priority for me. Thanks in advance, Paul [/INST]I'm somewhat hesitant whether to answer here, since it is not clear what you did. But it seems like you did not perform the operations you think you performed. It sounds like rather than restoring the backup to TestDatabase, you overwrote the existing production database. I hope that was a fresh backup! The reason that the database is now in the restoring state is presumably because you ran RESTORE with the NORECOVERY option. You need this option when you want to apply log backups to the full backup. And since there is talk of a tail-of-the-log backup, I think that this is what you want. You need to locate that file and apply it with this command: RESTORE LOG ProductionDatabase FROM DISK = 'C:\temp\logbackup.bak' WITH RECOVERY SQL Server will give you an error message if the log file does not fit with the current state of the database. Generally, if you want a test version of a production database, you would *never* restore that copy on the production server for multiple reasons. One is that your playing around in the test database should steal load from the production workload. But also very important is that this invites to accidents, as happened here. It is also bigger risk that you think that you are running something in the test database when you in fact are in production.</s>
<s>[INST]How to use inner join instead of left join on query below in case of data not exist on chemical master ? I work on sql server 2014 I need to use inner join instead of left join and update Haschemical i case of exist by haschemical or No in case of not exist on statement below i need to use inner join instead of left join because data is very big on table ExtractReports.dbo.FinalComplanceDataDelivery may be 20 million so query take too much time to execute update r set r.HasChemical=case when cm.partid is not null then 'HasChemical' else 'No' end from ExtractReports.dbo.FinalComplanceDataDelivery r with(nolock) left join Parts.ChemicalMaster cm with(nolock) on cm.partid=r.partid so How to do that Please ? [/INST]Cannot use INNER JOIN instead of LEFT JOIN, try to use OUTER APPLY instead of LEFT JOIN: update r set r.HasChemical=case when t.partid is not null then 'HasChemical' else 'No' end from ExtractReports.dbo.FinalComplanceDataDelivery r with(nolock) outer apply(select * from Parts.ChemicalMaster cm where cm.partid=r.partid) t</s>
<s>[INST]Convert C# to sql how to convert this to Sql Function string Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; string R = ""; long N = 324535354; // param do { R += Chars\[(int)(N % 0x3E)\]; } while ((N /= 0x3E) != 0); return R; [/INST]Try this function: create or alter function MyFunction( @N bigint ) returns varchar(max) as begin declare @R varchar(max) = '' declare @Chars varchar(max) = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' while 1 = 1 begin set @R += substring( @Chars, (@N % len(@Chars)) + 1, 1) set @N /= len(@Chars) if @N = 0 break end return @R end Example: select dbo.MyFunction( 324535354 )</s>
<s>[INST]Databases in same drive Hi All, How to tell or prove if colocated databases / database files in same disk / drive is having a performance problem. Sometimes, I see errorlog entries I/O requests taking more 15 secs warnings. Thanks, Bob [/INST]How can I leverage the sys.dm_io_virtual_file_stats to determine is there any IO perf problem? Well, since you see that message in the errorlog, you already know that you have an IO perf problem.... But apart from there, here is a stored procedure that I use for this purpose: CREATE OR ALTER PROCEDURE VFSMonitor AS SET NOCOUNT ON IF object_id('VFSData') IS NULL BEGIN CREATE TABLE VFSData ( sample_time datetime NOT NULL, database_id int NOT NULL, file_id int NOT NULL, sample_length_sec int NULL, num_of_reads bigint NULL, num_of_bytes_read bigint NULL, io_stall_read_ms bigint NULL, num_of_writes bigint NULL, num_of_bytes_written bigint NULL, io_stall_write_ms bigint NULL, io_stall bigint NULL, delta_size_on_disk bigint NULL, tot_num_of_reads bigint NOT NULL, tot_num_of_bytes_read bigint NOT NULL, tot_io_stall_read_ms bigint NOT NULL, tot_num_of_writes bigint NOT NULL, tot_num_of_bytes_written bigint NOT NULL, tot_io_stall_write_ms bigint NOT NULL, tot_io_stall bigint NOT NULL, size_on_disk_bytes bigint NOT NULL, CONSTRAINT pk_VFSData PRIMARY KEY (sample_time, database_id, file_id) ) CREATE INDEX database_ix ON VFSData(database_id, file_id) END DECLARE @latest datetime, @now datetime SELECT @latest = MAX(sample_time) FROM VFSData SELECT @now = getdate() INSERT INTO dbo.VFSData (sample_time, database_id, file_id, sample_length_sec, num_of_reads, num_of_bytes_read, io_stall_read_ms, num_of_writes, num_of_bytes_written, io_stall_write_ms, io_stall, delta_size_on_disk, tot_num_of_reads, tot_num_of_bytes_read, tot_io_stall_read_ms, tot_num_of_writes, tot_num_of_bytes_written, tot_io_stall_write_ms, tot_io_stall, size_on_disk_bytes) SELECT @now, fs.database_id, fs.file_id, datediff(ss, v.sample_time, @now), fs.num_of_reads - v.tot_num_of_reads, fs.num_of_bytes_read - v.tot_num_of_bytes_read, fs.io_stall_read_ms - v.tot_io_stall_read_ms, fs.num_of_writes - v.tot_num_of_writes, fs.num_of_bytes_written - v.tot_num_of_bytes_written, fs.io_stall_write_ms - v.tot_io_stall_write_ms, fs.io_stall - v.tot_io_stall, fs.size_on_disk_bytes - v.size_on_disk_bytes, fs.num_of_reads, fs.num_of_bytes_read, fs.io_stall_read_ms, fs.num_of_writes, fs.num_of_bytes_written, fs.io_stall_write_ms, fs.io_stall, fs.size_on_disk_bytes FROM sys.dm_io_virtual_file_stats(NULL, NULL) fs LEFT JOIN VFSData v ON fs.database_id = v.database_id AND fs.file_id = v.file_id AND v.sample_time = @latest Then I schedule to run every 10 or 15 minutes. Then I query it something like this: WITH VFStimes AS ( SELECT database_id, file_id, sample_time, num_of_reads, num_of_bytes_read, io_stall_read_ms, convert(decimal(20,1), 1E0*io_stall_read_ms / nullif(num_of_reads, 0)) AS read_time, num_of_writes, num_of_bytes_written, io_stall_write_ms, convert(decimal(20,1), 1E0*io_stall_write_ms / nullif(num_of_writes, 0)) AS write_time FROM VFSData ) SELECT * FROM VFStimes WHERE read_time > 10 OR write_time > 10 The idea with the filter is that access times below 10 ms are OK. Although, that limit is set with a spinning disk in mind; for an SSD, you may expect sub-millisecond times. Anyway, you can adjust the filter as you like. The idea is that the query will show you periods where you experienced slow disk access, and on which database and files.</s>
<s>[INST]Could not find server 'Servernamehere' in sys.servers. Verify that the correct server name was specified. Hello, we have two SQL servers, lets call them A and B. A is our old server, SQL Server 2014 and B is our new server, SQL Server 2019. Both servers are single servers as in not linked servers or connected to each other in any way. Our server guys backed up a database in server A and restored it to server B. When I try to execute a stored procedure on the new server B, I get an error saying **"Could not find server 'A' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers"** The particular stored procedure I tested, does not update anything in that database, although we do have those as well. There are no references to a particular server in the procedure code. Does anyone have an idea as to why this could've happened or how I could solve this without adding any linked server references into sys.servers? Best regards, Tunkkari[/INST]Possibly a synonym, that in turn points to a linked server. Check out what synonyms you have in that database, if any of those points to a linked server, and the queries in your proc, if any of those uses that synonym.</s>
<s>[INST]How to get all the objects in a table where the coordinates intersects with polygon with SQL Spatial Data I have an SQL table which called DATAB which contains thousands of objects ordered by the following colunms: [id] [angel] [latitude] [longitude] And i have this polygon set with STPolyFromText: DECLARE @polygon geography; SET @polygon = geography::STPolyFromText('POLYGON((35.22272601642959 32.78460617177918, 35.08671584135056 32.78345098011482, 35.11007112393986 32.873510861418836, 35.213109135363425 32.86716347866004, 35.22272601642959 32.78460617177918))', 4326); Now i want to make a SELECT query that returns all the rows where the waypoints (consisting of the longitude and latitude variables that are in each row) are on the border of the polygon or within the area of the polygon. Be aware that the variables latitude and longitude that are in each row are just numbers, not geography objects. I tried to do somthing like this: DECLARE @f geography; SELECT * FROM DATAB WHERE (SET @f = geography::STPointFromText('POINT('[longitude]' '[latitude]')', 4326)) ON (@geography.STIntersects(@f) = 1) Obviously, it failed. Any ideas?[/INST]Check this query: select * from DATAB where @polygon.STContains( geography::Point( latitude, longitude, @polygon.STSrid)) = 1</s>