text
stringlengths
209
10.7k
<s>[INST]Display Whole Days of month? I want to Display whole month Days ,whether data exit or not between given Date range. CREATE TABLE #ItemMasterFile(CodeItem INT,Descriptionitem VARCHAR(50),weight int); CREATE TABLE #Probale(BID INT,CodeItem INT,prdQTY INT,Orderno int,weight int,Entrydate date,DelID int); INSERT INTO #ItemMasterFile VALUES (1,'A',100) , (2,'B',100) , (3,'C',100) , (4,'D',100) , (5,'e',100) , (6,'f',100) , (7,'g',100) , (8,'h',100) , (9,'K',100) , (10,'L',100) , (11,'M',100); INSERT INTO #Probale VALUES (1,1,1,001,100,'2021-01-13',null) , (2,3,1,001,200,'2021-01-15',null) , (3,11,1,002,200,'2021-01-15',null) , (5,10,1,002,200,'2021-01-16',null) , (6,1,1,003,200,'2021-01-16',null) , (7,3,1,003,200,'2021-01-17',null); Declare @fromdate Date='2021-01-01' Declare @todate Date='2021-01-30' select I.Descriptionitem,isnull(sum(prdqty),0) as Qty,(P.Entrydate ) from #Probale P right outer join #ItemMasterFile I on I.CodeItem=P.Codeitem and P.Entrydate between @fromdate and @todate group by i.Descriptionitem,p.Entrydate [/INST]I don't know what result set you want exactly, but this query may get you started. Also look at the examples in my article. select I.Descriptionitem, d.d AS date, isnull(sum(prdQTY),0) as Qty from #ItemMasterFile I cross join (select d from NorthNumbers..Dates where d between @fromdate and @todate) AS d left join #Probale P on I.CodeItem=P.CodeItem and P.Entrydate = d.d group by I.Descriptionitem, d.d order by I.Descriptionitem, d.d</s>
<s>[INST]Ways on inserting data using stored procedure when TableName is dynamic Hi I have got a C# application that inserts data to different tables in the database, the table names are set dynamically, even the tables are created dynamically using stored procedure( which I managed to do). The table columns are fixed for all these tables. Should I use dynamic sql statement to do insert or are there other ways I can get this done. Advice and feedback appreciated[/INST]You should probably go back to the drawing board. In a relational database, a table is supposed to model a unique entity, with a unique set of attributes. So dynamically created tables kind goes across that idea. You say that all these tables have the same column. So I supposed there is something in the name that identifies the table. That something should probably be a key column in your one and single table. And your life will be a lot easier when you play by the rules.</s>
<s>[INST]Get SQL jobs list along with SQL scripts which is used in job HI Team, Is their any option to get the SQL jobs list along with SQL scripts which is used in job. Please help on same.[/INST]USE [msdb]; GO SELECT j.[name] AS [Job Name], s.[step_name] AS [Step_Name], s.[database_name] AS [Database Name], s.[command] AS [SQL Script] FROM [dbo].[sysjobs] AS j INNER JOIN [dbo].[sysjobsteps] AS s ON j.[job_id] = s.[job_id] WHERE j.[enabled] = 1 AND s.[subsystem] = 'TSQL' ORDER BY j.[name], s.[step_id];</s>
<s>[INST]What is the Polybase Architecture? Hi, I recently connected MS SQL Community 2019 with a local Oracle 19c database using Polybase. Polybase seems really insistent on using "Create External Table" to get access to the external database. So do I have to Create External Table for every foreign table I want to read? That seems really tedious and you have to deal with column data type issues between ms sql and the foreign database. So is the architecture of Polybase to individually connect every table in the foreign database one at a time? Prior approaches like Linked Server let you make one connection to Oracle and you could then just use queries to refer to all the table resources in the other database.[/INST]if you are connecting to say an Oracle database, it's kind of tedious. But if the data source is Hadoop or Spark or something which does not really have tables, it makes more sense, and I think is what has been driving this design. Then they have also added this for relational sources so that you can use the same interface all over the place. And there are some advantages with external tables over linked servers. One is that you can opt to only expose some of the columns on the remote source. Another is security. A linked server is not a securable, so once you have set up a linked server, every one can access the linked server as such. If you have self-mapping, it's not so bad, because everyone needs to have access on the other server. But if you have set up a login mapping and set it up for everyone - that's really bad. But manage so that only certain users that can access it - that's a nightmare. With external tables, you can grant SELECT just like you can on any other table, so that is really neat. But what I have found when testing is that latency is too high. The prime area is big data, and if you are to inject a 200 GB log file from Hadoop, there is no issue if there is a startup time of two seconds for the query. But it is unacceptable for a point-lookup query. So for traditional database application, Polybase is not that hot. That is my conclusion.</s>
<s>[INST]incorrect syntax near "server name\instance" expecting '(' or select I am still trying to learn/teach myself sql. I am adjusting a SCOM dashboard but 1 query gives an error. I am not sure why. I asked my DBA and he said for me to ask google. I get incorrect syntax near "server name\\instance" expecting '(' or select at sql.Database("OPSMGR2016DW\\OPSDBDW" I tried but still cannot figure it out. the full statement is: let Source = Sql.Database("OPSMGR2016DW\\OPSDBDW", "OperationsManagerDW", \[Query="SELECT DISTINCT DB_NAME(dovs.database_id) DBName,#(lf)mf.physical_name PhysicalFileLocation,#(lf)dovs.logical_volume_name AS LogicalName,#(lf)dovs.volume_mount_point AS Drive,#(lf)CONVERT(INT,dovs.available_bytes/1048576.0) AS FreeSpaceInMB#(lf)FROM sys.master_files mf#(lf)CROSS APPLY sys.dm_os_volume_stats(mf.database_id, mf.FILE_ID) dovs#(lf)Where DB_NAME(dovs.database_id) LIKE '%OperationsManager%'"\]), #"Renamed Columns" = Table.RenameColumns(Source,{{"DBName", "DB Name"}, {"PhysicalFileLocation", "Physical File Location"}, {"LogicalName", "Logical Name"}, {"FreeSpaceInMB", "Free Space (MB)"}}) in #"Renamed Columns" Please point me in the direction of what the proper format is. I also get the same thing in the area of Table.RenameColumns(Source,{ of incorrect syntax near 'Source'. Expecting '(' or Select [/INST]The M query looks all right to me, I would suspect the #(If) part in the sql query. We must make sure the query works in SQL level. Could you explain what the #(If) intended to do ? > SELECT DISTINCT DB_NAME(dovs.database_id) DBName,#(lf)mf.physical_name PhysicalFileLocation,#(lf)dovs.logical_volume_name AS LogicalName,#(lf)dovs.volume_mount_point AS Drive,#(lf)CONVERT(INT,dovs.available_bytes/1048576.0) AS FreeSpaceInMB#(lf)FROM sys.master_files mf#(lf)CROSS APPLY sys.dm_os_volume_stats(mf.database_id, mf.FILE_ID) dovs#(lf)Where DB_NAME(dovs.database_id) LIKE '%OperationsManager%'</s>
<s>[INST]Add two digit to first of another digits I have some tables in SQL and I want to add two digit (the two digit is a fixed number that is 13 ) to the first of all numbers in a some columns. I used this script but unfortunately it doesn't work accurately: for example I want to change 991105 to 13991105. my script is as follow: use SKraseh; UPDATE tblOrder SET tblOrder.DateReceived = 13 & [DateReceived] WHERE (((tblOrder.DateReceived)<>0)); [/INST]If *DateReceived* column in *int*, then: update tblOrder set DateReceived = '13' + cast(DateReceived as varchar(max)) -- or: concat('13', DateReceived) where DateReceived <> 0</s>
<s>[INST]Enabling TDE encryption for 1000 databases together Hi Team, I want to create a SQL script to enable TDE encryption for 100 databases together , by checking if is_encrypted field if 0 from dmv sys.dm_database_encryption_keys, then enable TDE. Regards,[/INST]This is something you could work from: DECLARE @db sysname, @sp_executesql nvarchar(500), @dbstmt nvarchar(MAX), @role sysname = 'ourrole' SELECT @dbstmt = 'CREATE DATABASE ENCRYPTION KEY WITH ALGORITHM = AES_128 ENCRYPTION BY SERVER CERTIFICATE MyServerCert; ALTER DATABASE CURRENT SET ENCRYPTION ON;' DECLARE dbcur CURSOR STATIC LOCAL FOR SELECT quotename(name) FROM sys.databases WHERE database_id > 4 AND state = 0 -- Only online databases AND is_encrypted = 0 ORDER BY name OPEN dbcur WHILE 1 = 1 BEGIN FETCH dbcur INTO @db IF @@fetch_status <> 0 BREAK SELECT @sp_executesql = @db + '.sys.sp_executesql' EXEC @sp_executesql @dbstmt END</s>
<s>[INST]Upgrade server Sql Server 2014 from Standard to Enterprise with Mirroing Hi everyone! I need some advise for solve next task: I have configured and fully worked Mirroring on MS SQLServer 2014 Standard Eddition. In last time i see what my APPS generate 100% overload Load CPU. On Server set 2 socet on 8 Core + HyperTrading on, in summ 24 logical core, all load on 100%. I want to solv this problrm by upgrade CPU, but how i understand 24 logical core maximum CPU on hardware server jn Standard Eddition, and i must ugrade license from Standard Eddition to Entrerprise. Please, advise me how can i solve this issue[/INST]To give a little more detailed answer to this question: No, going to Enterprise is not going to help poorly written code. And I've been in this game long enough to know that this is a case of poorly written code and/or bad indexing. But beside queries that needs tuning or better indexing, there is another way code can be poor. Some developers inline all parameters, so rather than sending: INSERT tbl(col1, col2, col3, ...) VALUES(@par1, @par2, @par3, ...) They send something like INSERT tbl(col1, col2, col3, ...) VALUES(14, 'Peter', 'Smith', ...) That is all parameters are inlined to the query. This means that every query needs to be compiled. Well, almost, very simple queries will be auto-parameterised. The correct fix in this case is to have the developers to clean up their act, which may take some time. But SQL Server provides a band-aid in this case. When it comes to upgrade, I think a better path is to go SQL 2016 or later. This is because with SQL 2016 you get Query Store, which makes it a lot easier to find slow-running queries. On SQL 2014, you need to runs traces or X-Event sessions to identify them, and these tools do add overhead themselves. Yes, there is a license cost for an upgrade. But I guess it's cheaper to go to SQL 2019 Standard than to SQL 2014 Enterprise. (And with SQL 2016+, you can replace mirroring with a Basic Availability Group.)</s>
<s>[INST]Not to sum last inserted Record. i want to not sum last inserted in table against I_ID column. I_ID=222 ,have three value 500 ,600 and 400. i have inserted last value 400 against I_ID ,which should not be sum and result will be 1100. Create TABLE #Tbl_IB_Cus_Libility (Li_ID int,I_ID int,I_Amt int) Insert into #Tbl_IB_Cus_Libility values (1,222,500) Insert into #Tbl_IB_Cus_Libility values (2,222,600) Insert into #Tbl_IB_Cus_Libility values (3,222,400) Insert into #Tbl_IB_Cus_Libility values (4,225,200) [/INST]Here's one option: SELECT li.I_ID, SUM(I_Amt) FROM #Tbl_IB_Cus_Libility AS li WHERE li.Li_ID <> (SELECT MAX(i.Li_id) FROM #Tbl_IB_Cus_Libility AS i WHERE i.I_ID = li.I_ID)</s>
<s>[INST]Upgrade form a sql express vesion to another Good evening, I have an application that is hosted an application on a sql 2008 express. Now the db has reached 4 Gb an so is no longer usable. I would like to know if it's possible to update in place the version to at least 2008R2 express edition to increase the database limit to 10 Gb kind regards[/INST]that is possible, but you need to be on Service Pack 4 to upgrade. There is little reason to go to SQL 2008 R2, since it is out of support just as much as SQL 2008 is. So SQL 2019 is a better bet, although there is a small risk that your application is using discontinued functionality.</s>
<s>[INST]RESTORE DATABASE Performance We are trying to restore a DB from a backup taken on ServerA to ServerB. The .bak file is 55.3GB. We are using the following TSQL: ALTER DATABASE [DB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE RESTORE DATABASE [DB] FROM DISK = N'\\share\Backup\DB_backup_2021_04_12_021002_3975291.bak' WITH FILE = 1, MOVE N'DB_Data' TO N'D:\\Program Files\\Microsoft SQL Server\\MSSQL15.MSSQLSERVER\\MSSQL\\DATA\\DB_Data.MDF', MOVE N'DB_Log' TO N'D:\\Program Files\\Microsoft SQL Server\\MSSQL15.MSSQLSERVER\\MSSQL\\DATA\\DB_Log.LDF', NOUNLOAD, REPLACE, STATS = 5 ALTER DATABASE [DB] SET MULTI_USER GO When running in SSMS it takes approximately 4:38 minutes to restore the DB. If I copy the file locally first, to the same destination drive as the SQL DB currently rests, it takes 1.77 minutes. Then I subsequently restore the file in SQL took another 2 minutes (all together about 3.5 minutes). When I tried the same thing with a 286GB backup file, it took **19 minutes** to (a) copy locally and (b) restore from local disk, as opposed to **1 hour** when restoring directly from the network share. I know the storage/share backend is not a bottleneck, since I can see how long a standard copy takes. Another anomaly: our source share is a enterprise storage array, when we can see (both in Wireshark) and via the storage monitoring that we are successfully utilizing ODX when copying the file over the network (as was done in the second test). But when we directly restore to SQL from network storage (as opposed to local disk), we don't see any ODX transfers **at all**! So, our questions are: 1. Why isn't ODX being utilized together with SQL? 2. Could that be the difference to explain the 1-step vs 2-step restore detailed above? [/INST]I am not familiar with the ODX feature in Windows. But I think SQL Server may not use ODX when restoring a database from a remote location, this is not only a simple data transfer, but also a restore operation. With the 2-step restore, first copy the backup file to the local with ODX can improve the transmission efficiency, and restore the database locally much faster than restoring from a network share. Restoring SQL Server databases from network storage relies on external network resources, and restore performance becomes unpredictable.</s>
<s>[INST]Delete permission denied for Db_owner Hello, I have a database user who is db_owner. However, any time he tries to delete rows from a table, he gets the Delete Permission denied. He is able to create new tables, drop them. But unable to delete from them. Please advise , how to resolve this. Thanks, Veena[/INST]I would suspect that there is a DENY in force somewhere. DENY takes precedence over GRANT. Even if you are db_owner.</s>
<s>[INST]Help with a Union Select statement I am wanting to Union the two Select statements below but I want the second statement to only bring back Addresses that are not in the result of the first select statement. I tried a AddressCode \<\> Addresscode in the second where clause but it's throwing an error. What am I doing wrong? Any help is appreciated. Thanks. Select Distinct PA.AddressCode As Location_CommonName, OT.OccupancyType As Location_OccupancyClassification,InspectionDate As Location_LastSurveyDate, NextInspectionDate As Location_NextSurveyDate, Recurrance As Location_SurveyFrequency, (SELECT Distinct InspectionType FROM dbo.InspectionTypes AS IT_1 WHERE (InspectionType = v_Activities.InspectionType)) As Location_ServiceType, IT.InspectionType As Location_ServiceType, PA.FullAddress as Location_Address1, PA.SubAddress as Location_Adress2, PA.City As Location_City, PA.StateAbbr AS Location_State, PA.Zip As Location_Zip, PA.PartyName As Contact_Name, PA.Email As Contact_Email, PA.Phone As Contact_DaytimePhone, PA.Cell As Contact_MobilePhone , PA.RoleType from v_PartyAddresses AS PA LEFT OUTER JOIN dbo.Addresses As Addr on PA.AddressId = Addr.Addressid LEFT OUTER JOIN dbo.OccupancyTypes As OT on Addr.OccupancyTypeId = OT.OccupancyTypeId Right OUTER JOIN dbo.v_Activities on Addr.AddressId = v_Activities.AddressId LEFT OUTER JOIN dbo.InspectionTypes As IT on v_Activities.InspectionTypeId = IT.InspectionTypeId Where PA.RoleType = 'Property Contact' and PA.AddInact = 'False' and APInactive = 'False' And v_Activities.InspectionCauseId \<\> '4611aa3c-17c2-4421-81bb-3e973786f26d' UNION Select Distinct PA2.AddressCode As Location_CommonName, OT2.OccupancyType As Location_OccupancyClassification,InspectionDate As Location_LastSurveyDate, NextInspectionDate As Location_NextSurveyDate, Recurrance As Location_SurveyFrequency, (SELECT Distinct InspectionType FROM dbo.InspectionTypes AS IT_1 WHERE (InspectionType = VA2.InspectionType)) As Location_ServiceType, IT2.InspectionType As Location_ServiceType, PA2.FullAddress as Location_Address1, PA2.SubAddress as Location_Adress2, PA2.City As Location_City, PA2.StateAbbr AS Location_State, PA2.Zip As Location_Zip, PA2.PartyName As Contact_Name, PA2.Email As Contact_Email, PA2.Phone As Contact_DaytimePhone, PA2.Cell As Contact_MobilePhone , PA2.RoleType from v_PartyAddresses AS PA2 LEFT OUTER JOIN dbo.Addresses As Addr2 on PA2.AddressId = Addr2.Addressid LEFT OUTER JOIN dbo.OccupancyTypes As OT2 on Addr2.OccupancyTypeId = OT2.OccupancyTypeId Right OUTER JOIN dbo.v_Activities as VA2 on Addr2.AddressId = VA2.AddressId LEFT OUTER JOIN dbo.InspectionTypes As IT2 on VA2.InspectionTypeId = IT2.InspectionTypeId **Where Addr.AddressCode \<\> Addr2.AddressCode** and PA2.RoleType = 'Owner' and PA2.AddInact = 'False' and APInactive = 'False' And VA2.InspectionCauseId \<\> '4611aa3c-17c2-4421-81bb-3e973786f26d' Order By PA.AddressCode, InspectionDate Desc, IT.InspectionType [/INST]I do not think you can use Addr.AddressCode \<\> Addr2.AddressCode when you use UNION since the alias Addr belongs to the first SELECT statement. Try this: ;WITH CTE_v_Activities AS ( SELECT * FROM ( SELECT AddressId, InspectionType, InspectionCauseId, InspectionDate, ..., ROW_NUMBER() OVER(PARTITION BY InspectionType, ... ORDER BY InspectionDate DESC) AS RowNumber FROM dbo.v_Activities ) AS t WHERE t.RowNumber = 1 ), CTE_01 AS ( Select Distinct PA.AddressCode As Location_CommonName, OT.OccupancyType As Location_OccupancyClassification,InspectionDate As Location_LastSurveyDate, NextInspectionDate As Location_NextSurveyDate, Recurrance As Location_SurveyFrequency, (SELECT Distinct InspectionType FROM dbo.InspectionTypes AS IT_1 WHERE (InspectionType = v_Activities.InspectionType)) As Location_ServiceType, IT.InspectionType As Location_ServiceType, PA.FullAddress as Location_Address1, PA.SubAddress as Location_Adress2, PA.City As Location_City, PA.StateAbbr AS Location_State, PA.Zip As Location_Zip, PA.PartyName As Contact_Name, PA.Email As Contact_Email, PA.Phone As Contact_DaytimePhone, PA.Cell As Contact_MobilePhone , PA.RoleType from v_PartyAddresses AS PA LEFT OUTER JOIN dbo.Addresses As Addr on PA.AddressId = Addr.Addressid LEFT OUTER JOIN dbo.OccupancyTypes As OT on Addr.OccupancyTypeId = OT.OccupancyTypeId Right OUTER JOIN CTE_v_Activities AS v_Activities on Addr.AddressId = v_Activities.AddressId LEFT OUTER JOIN dbo.InspectionTypes As IT on v_Activities.InspectionTypeId = IT.InspectionTypeId Where PA.RoleType = 'Property Contact' and PA.AddInact = 'False' and APInactive = 'False' And v_Activities.InspectionCauseId <> '4611aa3c-17c2-4421-81bb-3e973786f26d' ), CTE_02 AS ( Select Distinct PA2.AddressCode As Location_CommonName, OT2.OccupancyType As Location_OccupancyClassification,InspectionDate As Location_LastSurveyDate, NextInspectionDate As Location_NextSurveyDate, Recurrance As Location_SurveyFrequency, (SELECT Distinct InspectionType FROM dbo.InspectionTypes AS IT_1 WHERE (InspectionType = VA2.InspectionType)) As Location_ServiceType, IT2.InspectionType As Location_ServiceType, PA2.FullAddress as Location_Address1, PA2.SubAddress as Location_Adress2, PA2.City As Location_City, PA2.StateAbbr AS Location_State, PA2.Zip As Location_Zip, PA2.PartyName As Contact_Name, PA2.Email As Contact_Email, PA2.Phone As Contact_DaytimePhone, PA2.Cell As Contact_MobilePhone , PA2.RoleType from v_PartyAddresses AS PA2 LEFT OUTER JOIN dbo.Addresses As Addr2 on PA2.AddressId = Addr2.Addressid LEFT OUTER JOIN dbo.OccupancyTypes As OT2 on Addr2.OccupancyTypeId = OT2.OccupancyTypeId Right OUTER JOIN CTE_v_Activities as VA2 on Addr2.AddressId = VA2.AddressId LEFT OUTER JOIN dbo.InspectionTypes As IT2 on VA2.InspectionTypeId = IT2.InspectionTypeId Where PA2.RoleType = 'Owner' and PA2.AddInact = 'False' and APInactive = 'False' And VA2.InspectionCauseId <> '4611aa3c-17c2-4421-81bb-3e973786f26d' ) SELECT * FROM CTE_01 UNION SELECT * FROM CTE_02 WHERE AddressCode NOT IN (SELECT AddressCode FROM CTE_01) ORDER BY AddressCode, InspectionDate Desc, InspectionType</s>
<s>[INST]will the windows update fail Our company has set up windows automtically download for some servers. One is: Security Update for SQL Server 2019 RTM CU (KB4583459) But my SQL server is already 2019 CU8, if I click to install all downloaded patches, this will run. Will it recognize my server has already been CU8 and not run the patch, or it will still run the patch even it is no longer the RMT CU any more? Or will it fail? Thanks[/INST]Whether it will fail with an error or silently be ignored, I don't know. That depends on how smart Windows Update is. But it will not be installed. There is a security fix for CU8 as well, but I think you are better of with applying CU10, which is the most recent CU for SQL 2019.</s>
<s>[INST]SSMS - Shared Components Hi, I was wondering if shared components of Sql Server Management Studio get updated along with any SSMS updates if available? EG if you update SSMS, Visual Studio Tools for Applications will get updated if there is an update for it.[/INST]When updating/installing a new version of SSMS, the shared components on the machine will be detected. If there is an update to the shared component, updating SSMS will update the shared component. When I install the latest version of SSMS (18.9.1), I will see the installation interface showing the progress of the shared components, and after the installation is complete, I can find that the installation dates of some shared components have changed in the control panel.</s>
<s>[INST]Unable to Telnet SQL PORT -SQL Server 2019 Developer edition with CU9 Hi Team, I am using a SQL Cluster with single now. Microsoft SQL Server 2019 (RTM-CU10) (KB5001090) - 15.0.4123.1 (X64) Mar 22 2021 18:10:24 Copyright (C) 2019 Microsoft Corporation Developer Edition (64-bit) on Windows Server 2019 Datacenter 10.0 <X64> (Build 17763: ) (Hypervisor) I am able to connect my SQL Server from SQL Studio Manager but while trying to telnet localhost 1433 or telnet A.B.C.D 1433 ( Consider A.B.C.D as IP Address ) , Giving Error " Connecting To 192.168.157.32...Could not open connection to the host, TCP/IP and named pipes are already enabled. -Regards, Bhupendra [/INST]Bhupendrakumar G\. \(TR Technology\) , Was your SQL Server cluster installed as a default instance or named instance? Please make sure it is listening on port 1433. > Giving Error " Connecting To 192.168.157.32...Could not open connection to the host, Is 192.168.157.32 the IP address of your SQL Cluster? If it is not, please try to `telnet <sql cluster name or sql cluster ip> port`.</s>
<s>[INST]making a stored procedure interactive is there a way for a stored procedure to move on to the next statement or maybe loop iteration only after person running it hits a return button or maybe types GO and then return? I think i've seen something like this before but that solution might only have allowed one interaction. the proc will update some data between a before select and after select ad if the operator doesnt like something he/she sees, there would be an option to stop.[/INST]No. T-SQL does not support user interaction at all. One way to do this would be to write a script (outside SQL) that executes some SQL, prompts the user and then executes some more SQL. Of course the feasibility of this is highly dependent upon what you're trying to do. It might also be possible to do it via SSIS task that the user runs but I've never looked to see if SSIS has any interactive components. Having said that I will point out that, if enabled on the server, then you can call out to the shell using something like xp_cmdshell. However this is just screaming of insecure and therefore not on by default AFAIK and no reasonable DBA would enable it anyway. However if they did then in theory you could trigger a prompt by shelling out to wscript. But honestly that wouldn't make sense to me. Furthermore the SQL Server instance is probably running on a remote server as a service so I'm not even sure a shell script would work as the UI would pop up on a screen the user doesn't have access to. SSMS/Azure Data Studio and probably any other query execution program would not get notified of any UI.</s>
<s>[INST]can results be in order of IN keyword condtions? i'm using item numbers for the IN conditions to return a total of each item number ordered for sales orders between 2 dates. i need the results to be in the same order the item numbers appear in the IN statement. the item numbers in the IN statement are not sorted in any way. is this possible? if i use a date range i get a different order of results than if i use no date range and just the item numbers. but, neither is correct. [/INST]when i look at the tempdb database, there is a table dbo#tbl but it has numerous underscore characters follwed by 00000000000A as the table name This is because when you say `CREATE TABLE #temp`, SQL Server tacks on all these underscores and these hex digits to make the name unique, so that to two processes can say `CREATE TABLE #temp` without interfering with each other. But that is something that happens under the covers, and you don't really have to bother.</s>
<s>[INST]SQL Server 2017 CU 23 update query Hi, Few weeks back we had applied SQL Server 2017 RTM CU(KB4583457) GDR on our Prod system which is running on SQL Server 2017 CU22. Now with SQL Server 2017 CU 23 release, can we directly apply this patch on top of GDR update? or should we rollback SQL Server 2017 RTM CU(KB4583457) GDR and then apply CU23. Please clarify. Regards. Var[/INST]CU = Cumulative Update and that means CU 23 includes all previoussly released patches; no need to rollback anything.</s>
<s>[INST]any effect of changing sa password hi every one.I have to change the sa password In sql server. Does changing the password have an effect on sql server jobs or any other object on the server? Is the sql server version important for the effect of this change?[/INST]Not on jobs or any other internal process. But by my experience several people uses "sa" for application logins, by fail. And so I would say: Change it and see which app uses "sa", which shouldn't; that' a very high security issue if they do.</s>
<s>[INST]Database alert if no data added Hi friends, I’d like to have your help. I have a SQL Server database, and a table dbo.OnData on it. **I would like to receive an email alert from my database if:** - **within a range of 30mins from 8:00:00 a.m. opening time and default time per day** - **AND 30mins after the time of the last Add in the dbo.OnData table,** t**here are no additions to the dbo.OnData table, a message like "from such time to such time, No Add to dbo.OnData table".** **Example:** Opening at 08:00:00, From 08:00:00 to 08:30:00, there is no addition in the table, => Alert From 08:30:00 to 9:00:00, 1 line has been added at 08:35:00 => No alert From 08:35:00 (time when the last rows were added) to 08:35:00 + 00:30:00 i.e. 09:05:00, there is no addition in the table, => Alert From 09:05:00 to 09:35:00, there are 20 lines added, last line time at 09:15:00 => No alert From 09:15:00 to 09:45:00, there is no addition in the table => Alert Would it be possible to do this? Thanks in advance friends, [/INST]it is possible. One way is to create a SQL Server Agent job that does a SELECT from your table and keep track of the most recently added row (you have created a table for this purpose). Then the next time this job runs (it runs every minute, for instance), it will check the most recently added row and when that was. If the time is greater then 30 minutes, then use sp_send_dbmail to send an email.</s>
<s>[INST]alternate to SQL Server Compact Edition Hello, Is there an alternate to SQL Server Compact Edition which won't be supported by MS beyond **July 2021**. It is needed for our Windows Desktop product built in C#.Net. [/INST]SQL Server Express is a free edition of SQL Server, ideal for development and production for desktop, web, and small server applications</s>
<s>[INST]Script to backup database on the last day of the week and last day of the month Hi All, Could you please help provide script which backups up the databases like below. 1. Daily full backup should happen to **Daily backup** folder. 2. Last day of the week backup should happen **Last day of Week** folder. 3. Last day of the month backup should happen to **Last day of month** folder. If you could help in the logic that need to be used for above it would be helpful. Thanks in Advance! [/INST]Use the IF statement to check if the current date is the last day of the month or the last day of the week. Otherwise it is a normal day: -- Last day of the month IF CONVERT(date, GETDATE()) = EOMONTH(GETDATE()) BEGIN BACKUP DATABASE TestDB TO DISK = 'C:\SQLServerBackups\Last_Day_Of_Month\TestDB_YYYYMMDD.bak' WITH FORMAT; -- Last day of the week ELSE IF DATEPART(weekday, GETDATE()) % 7 = 0 BEGIN BACKUP DATABASE TestDB TO DISK = 'C:\SQLServerBackups\Last_Day_Of_Week\TestDB_YYYYMMDD.bak' WITH FORMAT; -- Daily ELSE BEGIN BACKUP DATABASE TestDB TO DISK = 'C:\SQLServerBackups\Daily_Backup\TestDB_YYYYMMDD.bak' WITH FORMAT;</s>
<s>[INST]Counting the number of Diagnosis codes by context ,Specialty and provider Hi Team, Hope you are doing well!.. I am trying to I am trying to count the number of diagnosis codes by context ,Specialty and provider..Can you please help me here.. Please find below the input and the output tables . **Input table** create table ##input (contextid int, visitbillid int , specialty varchar (20), provider varchar (20), diagnosiscode varchar (1000) ) insert into ##input values ('78','34','OB','TITLO','Z01419,Z951,E663,M810'), ('78','35','OB','TITLO','Z01419,N952,E663,E559'), ('78','36','OB','TITLO','Z01419,E559,E663,Z1151,Z780,Z86010'), ('78','37','OB','TITLO','Z01411,N952,E663,E559,Z780,Z713'), ('712','89','Medicine','JAGLO','Z00129,Z130,Z1388,Z713,Z6853'), ('712','90','Medicine','JAGLO','Z00129,Z713,Z7182,Z6852'), ('712','91','Medicine','JAGLO','Z00121,H50011,Z713,Z6851,Z7182'), ('712','92','Medicine','JAGLO','H6693,T85628A,Y838') **Output table** create table ##output (contextid int, specialty varchar(20), provider varchar(20), diagnosiscode varchar(500), countofdiagnosiscode int) insert into ##output values ('78','OB','TITLO','Z01419','3'), ('78','OB','TITLO','Z951','1'), ('78','OB','TITLO','E663','4'), ('78','OB','TITLO','M810','1'), ('78','OB','TITLO','N952','2'), ('78','OB','TITLO','E559','3'), ('78','OB','TITLO','Z1151','1'), ('78','OB','TITLO','Z780','2'), ('78','OB','TITLO','286010','1'), ('78','OB','TITLO','Z713','1'), ('712','Medicine','JAGLO','Z00129','2'), ('712','Medicine','JAGLO','Z130','1'), ('712','Medicine','JAGLO','Z1388','1'), ('712','Medicine','JAGLO','Z713','3'), ('712','Medicine','JAGLO','Z6853','1'), ('712','Medicine','JAGLO','Z7182','2'), ('712','Medicine','JAGLO','Z6852','1'), ('712','Medicine','JAGLO','Z00121','1'), ('712','Medicine','JAGLO','H50011','1'), ('712','Medicine','JAGLO','Z6851','1'), ('712','Medicine','JAGLO','Z7182','1'), ('712','Medicine','JAGLO','H6693','1'), ('712','Medicine','JAGLO','T85628A','1'), ('712','Medicine','JAGLO','Y838','1') Thanks, Arun[/INST]Check this query: select contextid, specialty, provider, t.value as diagnosiscode , count(*) as countofdiagnosiscode from ##input cross apply string_split(diagnosiscode, ',') t group by contextid, specialty, provider, t.value order by contextid, specialty, provider, diagnosiscode Prepend *'insert into...'* to insert the results to *##output* table.</s>
<s>[INST]An expression of non-boolean type specified in a context where a condition is expected Hi, I have an issue with this stored procedure (code below), it returns me the following error: **An expression of non-boolean type specified in a context where a condition is expected, near 'seque'.** Can you please help me with it ? Thank you DECLARE @table_name nvarchar(max); DECLARE @sequence nvarchar(max); DECLARE @batch_no nvarchar(max); DECLARE @SQL nvarchar(500); DECLARE @ParmDef nvarchar(500) SELECT @SQL ='select @batch_no_output=(select max(batch_no) from [glb_ops_tsq_audit].[batch]), @table_name_out=a.table_name, @sequence_out=a.sequence from [glb_ops_tsq_audit].[table_config] a left join (select table_name,sequence,max_batch from (select table_name,sequence,max(batch_no) max_batch from [glb_ops_tsq_audit].[batch_processing_log] group by table_name,sequence) a where max_batch=(select(max(batch_no)) aa from [glb_ops_tsq_audit].[batch])) b on trim(a.table_name)=trim(a.table_name) and a.sequence=b.sequence where b.table_name is null' ; SET @ParmDef = N'@table_name_out nvarchar(max) OUTPUT,@sequence_out nvarchar(max) OUTPUT,@batch_no_output nvarchar(max) OUTPUT'; EXEC sp_executesql @SQL, @ParmDef, @table_name_out=@table_name OUTPUT,@sequence_out=@sequence OUTPUT,@batch_no_output=@batch_no OUTPUT; select @batch_no, @table_name ,@sequence [/INST]Try increasing the size: DECLARE @SQL nvarchar(max) Show the new errors, if any.</s>
<s>[INST]How to attach an SQL Server database containing File Stream from one server to another server? I have a database, there is no backup. This database was created on SQL Server version 14 and that server is no longer available. I have the MDF, LDF and the filestream.hdr files. Now I want to attached this database to SQL Server 2017. As you guess it, the attached process fails. If I try to attached from Management Studio, I get an error that the file stream folder cannot be located. However, if I point to the folder in script, I get File Activation Error. CREATE DATABASE [MyDB] ON ( FILENAME = N'D:\MSSQL14.InstanceName\MSSQL\DATA\MyDB.mdf' ), ( FILENAME = N'L:\MSSQL14.InstanceName\MSSQL\Log\MyDB_log.ldf' ), FILEGROUP [MyFileStream] CONTAINS FILESTREAM DEFAULT ( NAME = N'MyFileStream', FILENAME = N'D:\MSSQL14.InstanceName\MSSQL\DATA\FileStreamFolder' ) FOR ATTACH GO [/INST]Only filestream.hdr? Not the actual files? What you can try is to create a new database, and then take that database offline, and copy the files of this database over the files of the new database. No guarantees, though.</s>
<s>[INST]How to find out if a database is being used? Hi, We have a database on a server, but we are unsure if anything is actually using it. Is there a way to monitor and store connections to the database? I was thinking of running it for about three weeks and if nothing connects, then taking it offline. Thanks[/INST]You can set up a trace or an X-Event session capturing RPC:Starting and SQL:BatchStarting and which is filtered for these databases. You may also have to filter out things like the Telemetry session if you are on SQL 2016 or later. Beware that even if the trace/X-Event session is filtered it will affect all processes, and if this is a system with very many, but, short commands, this can incur a significant overhead.</s>
<s>[INST]Copying SQL Table with Service Provider I am attempting to move some SQL tables from an archive DB to a new DB in use by corporate dashboards. The archive is a linked server with OraOLEDB.Oracle as a provider. When I attempt to copy my table I get the following error: The OLE DB provider "OraOLEDB.Oracle" for linked server "P2DATABASE" supplied invalid metadata for column "CREATE_DATE_TIME". The data type is not supported Looking at the schema there is no column CREATE_DATE_TIME but can still not copy the data over. I have been unable to use OPENQUERY to move the data. Thanks,[/INST]There is not a ton of information to work from here, and I know very little about Oracle. If am a to make a guess there is a computed column or view on the Oracle side involved here. Rather than using four-part notation, it may be better to use OPENQUERY: SELECT *. FROM OPENQUERY(MyOracle, 'SELECT col1, col2, col3 FROM tbl') The query inside OPENQUERY runs on Oracle, which means that you use Oracle syntax. This also means that you can convert troublesome data types to something that SQL Server can digest. For instance, you can convert dates to strings. Note that the `timestamp` datatypes in Oracle and SQL Server are entirely unrelated. The most closest data type to Oracle's `timestamp` in SQL server is `datetime2`, but vaguely recall that Oracle supports a broader range which causes problems. Anyway, start with a straight rewrite with OPENQUERY and work from there.</s>
<s>[INST]alter recovery model to simple and effect on cdc enabled databases we need to alter the recover model to simple due to some reasons with space issues. some of the databases have cdc enabled on them, will altering from full to simple have any impact. after changing the recovery model to simple, do i need to apply full backup[/INST]CDC = Change Data Capture don't have a relation/dependency to the recovery model of the database, so you can change it without impact. When changing simple => full then it's mandatory to run a full backup before you can make log backup; the other way round it's not mandatory, but having an additional backup is never wrong.</s>
<s>[INST]Revert varbinary(max) data back after convert to varchar(max) I have a sql server column with varbinary(max). I converted it to varchar(max) for ssis package to move it to another table which is also varbinary(max). The value that was inserted is not correct and I want to revert back to the original value. So the original value was '0x504B03041400060008000000210094DE92' with SELECT convert(varchar(MAX),items,2) AS items, I got 0x35303442303330343134303030363030BB. The application is not working so I want to revert back to the original value. can anybody help me here.[/INST]you never have the incorrect value in your script... Working from Viorel's script, here is an example how it may have happened, and how to repair it.. declare @original varbinary(max) = 0x504B03041400060008000000210094DE92 declare @converted varchar(max) = convert(varchar(max), @original, 2) declare @accident varbinary(max) = convert(varbinary(max), @converted) declare @revstring varchar(max) = convert(varchar(max), @accident) declare @revbinary varbinary(max) = convert(varbinary(max), @revstring, 2) select @original, @converted, @accident, @revstring, @revbinary The key is that if you convert from varchar to binary without a style code, the characters will be copied bit by bit. That is the string '5' will be 0x35 - which is the binary representation of the character '5'. To convert to and from hexstrings you need the style codes 1 or 2.</s>
<s>[INST]SQL Column AutoFill I have a sql table called tktproc with the following column proc_date with data type of datetime. How can i autofill column acct_period from proc_date in the following format YYYYMM?[/INST]In case of ancient servers, check the next statement: \_alter table tktproc add acct_period as (cast(YEAR(proc_date) \* 100 + MONTH(proc_date) as varchar(max)))\_ Show the error messages.</s>
<s>[INST]Best way to export data with LOB columns. Greetings. I need to export several tables with LOB columns into new tables for long winded reasons. My current example has two XML columns on it, is 10 million records, and took about 12 hours to load through a job that calls SSIS. A few fun facts: 1. Nobody else is on the box, resources are fine, no blocking, etc. 2. The source and destination are on the same box, the only real difference is they're on different disks, but this is a VM anyways, so not sure that really matters. 3. From googling I'm under the impression this is totally common. I've seen a couple suggestions, but not really clear on a common solution. Questions: 1. Are there any settings within SSIS itself I can tweak to speed this up? 2. Is there an better option than SSIS -- Bulk Insert, Insert...Select, etc.? 3. Is there any reason to think something goofy like export all columns but LOB columns first, then do an update for LOB columns only would be faster? 4. Because resources are fine, is there any reason to not export several tables at the same time, as there won't be resource contention? 5. Editing the source to be an actual query instead of just relying on the GUI, I can convert one of the columns as such. If I use 1024, I get a warning about the column being too small for XML, but if I stick to 2048 I don't. Is this safe? Will it perform better? convert(varchar(2048), [RequestHashInfo]) as RequestHashInfo, 6. My wait types are constantly ASYNC_NETWORK_IO -- why would this be under these circumstances? Thanks! [/INST]My wait types are constantly ASYNC_NETWORK_IO -- why would this be under these circumstances? ASYNC_NETWORK_IO means that SQL Server is waiting for the client to pick up data. It could be due to slow network, but more likely the client is slow with processing the data. I'm not sure why you brought in SSIS here. It sounds like you are copying the data to tables in the same database. In that case, it is probably not a good idea to extract the data to a client. I would do this with INSERT SELECT, having only the clustered in place, adding non-clustered indexes once data has been copied. I would also considering inserting the rows in batches to keep down the strain on the transaction log. But it is important that the batches are defined through the clustered index, since you will repeat a scan again and again. How many rows there should be per batch, depends on the size of those LOBs. Look at the total size of the table with sp_spaceused (the `reserved` column). Then compute the batch size, so that a batch is 500 MB in size on average. (There is no science behind that number; but I picked something which is not too big, nor too small.)</s>
<s>[INST]Table's design Hi everybody, I'm trying to figure out why one of the tables I took a quick look today is designed this way and does it make any sense or not. The table currently has ~42 mln rows. It has bigint identity column defined as primary key (non clustered) and it also has varchar(38) column which has a clustered index for it (the max length of this column is currently 18 and that column is not unique). Does it really make any sense to have the clustered index on that varchar(38) column instead of the bigint identity unique column? Also, that table is a temporal table. Assuming that we would need to change the index, is it possible to estimate how long the re-index process will take and what would be the correct way to swap the clustered vs non clustered? The other question is simpler - I noticed that the names of the constraints use the wrong names (it looks like that table originally was named differently) - is it a simple matter of just renaming the constraints? Thanks in advance.[/INST]It could very well be that the chosen column for the clustered index is correct and valid. It all depends on how the table is queried - for example, if the majority of the queries use that column in the where clause to identify the row to be returned - or that column is used in a range for the majority of queries. A good example is a datetime column as the clustered index - when most queries use a date range (e.g. last months data, last weeks, yesterdays, etc.). Unless you are seeing performance issues on most of the queries accessing this table - I wouldn't be looking to change it, especially if the only reason is because you want the PK to also be the clustered index. It doesn't have to be and often that is not a good practice.</s>
<s>[INST]AlwaysOn with backword campatibilty I have an environment with databases of different compatibility 100 - 140 running on a SQL 2017 server. 1. Will the databases with 100 compatibility support alwayson. 2. Is it advisable to include databases with different compatibility in an availability group. [/INST]1. Yes, they will. 2. There is no issue with mixing compatibility levels in an AG. The compatibility level controls things like what language features that are available, behavioural changes, and how the optimizer works. But it has nothing to do with the physical structure of the databsae.</s>
<s>[INST]Delete using JOIN vs using subquery performance there are two query for delete delete from tableA a join tableb b on a.col1=b.col1 vs delete from tableA a where col1 in (select col1 from tableb) which one is performed faster. ?[/INST]answer: it depends. Somewhat longer answer: for your actual case, you will need to benchmark. If I am to make a guess, I would guess that you get the same performance in most cases.</s>
<s>[INST]Writing stored procedure Hi All, I want to write a stored procedure or sql query for the following functionality: - Select the branch name from a existing table (table name is reports) - loop through each branch name and get the latest date - Check if the test date exists for that branch, if not insert into table (new table created. table name: TestResultAvailibiltyMaster) Please let me know how can I achieve this in Sql. Kindly waiting for your response. Thanks, Santosh [/INST]It is strongly recommended for you to provide enough sample data to illustrate all angles of the problem and the expected output. Then we could avoid guessing and correcting again and again. Please refer below updated one: drop table if exists reports, TestResultAvailibiltyMaster create table reports (branchname varchar(20), testdate date) insert into reports values ('Work_Branch','2021-05-30'), ('Work_Branch','2021-06-01'), ('Test_Branch','2021-05-31'), ('Test_Branch','2021-06-02') create table TestResultAvailibiltyMaster (branchname varchar(20), testdate date, ResultAvailability time) insert into TestResultAvailibiltyMaster values ('Work_Branch','2021-06-01','21:10:10') Method One using not exists: insert into TestResultAvailibiltyMaster select a.*,FORMAT(GETDATE(),'hh:mm:ss') ResultAvailability from (select branchname,max(testdate) testdate from reports group by branchname) a where not exists (select 1 from TestResultAvailibiltyMaster b where b.branchname=a.branchname and b.testdate=a.testdate) Method Two using left join: insert into TestResultAvailibiltyMaster select a.*,FORMAT(GETDATE(),'hh:mm:ss') ResultAvailability from (select branchname,max(testdate) testdate from reports group by branchname) a left join TestResultAvailibiltyMaster b on b.branchname=a.branchname and b.testdate=a.testdate where b.branchname is null</s>
<s>[INST]table data script file with date range Hi, I need specific table data script file '.sql' file only specific date range (like insert into) when i get it through database -> task -> generate script it give all table entries. but i need only specific date range. note: i dont have admin rights Thanks [/INST]why did you not try the suggestion that I mentioned above. Select the data only specific date range , then insert the data into a new table, then you can get a table with the data that specific date range. If my suggestion did not meet your requirement, please feel free to let me know.</s>
<s>[INST]syntax error Unclosed quotation mark after the character string I work on sql server 2012 i face syntax error when run query below SELECT PartID,Code,Co.CodeTypeID,Co.RevisionID,Co.ZPLID,Count(1) as ConCount FROM [ExtractReports].dbo.PartAttributes PM INNER JOIN [ExtractReports].dbo.Condition Co ON Co.ZfeatureKey = PM.ZfeatureKey Where (1=1 and (PM.ZfeatureKey= 1506990046 And Name ='Aluminum') Or (PM.ZfeatureKey= 1506990006 And Name ='Unthreaded') Or (PM.ZfeatureKey= 1506990016 And Name Not In('#4-40','#6-32','#1-64','#1-72','#8-32','#10-32','#2-56','#2-64','#3-48','#4-36','#3-56','#4-48','#6-40','#0-80','#5-40','#10-24','#12-24','#2-28','#4-20','#8','#4','#6','#2','#10','#14','#10-16','#2-32','#0.25-20','#8-18','#12-14','#4-4','#6-13',') ) Group By PartID,Code,Co.CodeTypeID,Co.RevisionID,Co.ZPLID Having Count(1)>= 3 so after un query above i get these syntax error so how to solve this issue and why this error done Msg 105, Level 15, State 1, Line 4 Unclosed quotation mark after the character string ') ) Group By PartID,Code,Co.CodeTypeID,Co.RevisionID,Co.ZPLID Having Count(1)>= 3 '. Msg 102, Level 15, State 1, Line 4 Incorrect syntax near ') ) Group By PartID,Code,Co.CodeTypeID,Co.RevisionID,Co.ZPLID Having Count(1)>= 3 [/INST]12-14','#4-4','#6-13',') ) Group Here it is; in IN clause ends with a comma + a single apostrophe, without a closing apostrophe.</s>
<s>[INST]backup file size Experts , Can you please share a script which can extract the database backup(Full and Log) size for all the backups showing in the backup history table date and timewise[/INST]You can the backup file information from system database "msdb" table backupfile, for example SELECT * FROM msdb.dbo.backupset as BS INNER JOIN msdb.dbo.backupfile AS BF ON BS.backup_set_id = BF.backup_set_id</s>
<s>[INST]Copying files negative impacts on active SQL Server? Hello, I have one folder that holds all of our SQL Server .bak backup files and aiming to set up a daily job to copy this folder and all files to another different server disk location. This folder is pretty large and say it takes 1 hour to finish copying. During this 1 hour of copying will it affect performance or any other things to be aware-concern on the current active SQL Server?...should it be done off hours? Thanks in advance.[/INST]During this 1 hour of copying will it affect performance Of course it will, copying files causes a lot of disk I/O and network traffic; no action is for free in term of resources.</s>
<s>[INST]Operand data type varchar is invalid for sum operator. i am facing error on below line ,want comma in value ( 48,950.00) Operand data type varchar is invalid for sum operator. sum ( CONVERT(Varchar(50), Cast(tn.Debit as money),1)) [/INST]SUM can be used with numeric columns only. Null values are ignored. Try this CONVERT(Varchar(50), sum ( Cast(tn.Debit as money)),1))</s>
<s>[INST]Issue to query Hi, What is reason of error like > Msg 8151, Level 16, State 0, Line 49 > Both a PRIMARY KEY and UNIQUE constraint have been defined for column 'compaddr', table 'dbo.user_main'. Only one is allowed. on this query? > CREATE TABLE [dbo].[user_main] ON [PRIMARY] > SET ANSI_PADDING ON > ALTER TABLE [dbo].[user_main] ADD [photo_file_fullname] [varchar] NULL > ALTER TABLE [dbo].[user_main] ADD [photo_file_name] [varchar] NULL > ALTER TABLE [dbo].[user_main] ADD [photo_file_ext] [varchar] NULL > ALTER TABLE [dbo].[user_main] ADD [addr1] [varchar] NULL > ALTER TABLE [dbo].[user_main] ADD [addr2] [varchar] NULL > ALTER TABLE [dbo].[user_main] ADD [company_id] [int] NULL > ALTER TABLE [dbo].[user_main] ADD [company] [nvarchar] NULL > ALTER TABLE [dbo].[user_main] ADD [notify_flag] [bit] NULL > ALTER TABLE [dbo].[user_main] ADD [usertype] [nvarchar] NOT NULL > ALTER TABLE [dbo].[user_main] ADD [compname] [nvarchar] NULL > ALTER TABLE [dbo].[user_main] ADD [compaddr] [nvarchar] NULL > PRIMARY KEY CLUSTERED > ( > [user_id] ASC > )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] > CONSTRAINT [cons_user_main2] UNIQUE NONCLUSTERED > ( > [user_name] ASC > )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] > > GO > > SET ANSI_PADDING OFF > GO > > ALTER TABLE [dbo].[user_main] ADD CONSTRAINT [df_approvedbyAdmin] DEFAULT ((1)) FOR [approvedbyAdmin] > GO > > ALTER TABLE [dbo].[user_main] ADD DEFAULT (' ') FOR [usertype] > GO > > ALTER TABLE [dbo].[user_main] ADD DEFAULT (' ') FOR [compname] > GO > > ALTER TABLE [dbo].[user_main] ADD DEFAULT (' ') FOR [compaddr] > GO > [/INST]You can do this, but you must create the UNIQUE constraint in a separate statement. So the end of your CREATE TABLE statement would be ALTER TABLE \[dbo\].\[user_main\] ADD \[compname\] [nvarchar] NULL ALTER TABLE \[dbo\].\[user_main\] ADD \[compaddr\] [nvarchar] NULL PRIMARY KEY CLUSTERED ( \[user_id\] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON \[PRIMARY\] GO and then you would follow that with ALTER TABLE [dbo].[user_main] ADD CONSTRAINT [cons_user_main2] UNIQUE NONCLUSTERED ( [user_name] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO</s>
<s>[INST]XML into primary and seconday table Hi, I have a xml data like below \<Activity> \<ID>2\</ID> \<Start>01/01/2012 13:00\</Start> \<Quantity>1\</Quantity> \<Observation> \<Code>14\</Code> \<Value>5\</Value> \</Observation> \<Observation> \<Code>76\</Code> \<Value>5\</Value> \</Observation> \</Activity> \<Activity> \<ID>3\</ID> \<Start>01/01/2012 13:00\</Start> \<Quantity>1\</Quantity> \<Observation> \<Code>14\</Code> \<Value>10\</Value> \</Observation> \</Activity> \<Activity> \<ID>4\</ID> \<Start>01/01/2012 13:00\</Start> \<Quantity>1\</Quantity> \</Activity> I have two table like 'Activity' as primary table and 'Observation' as a foreign key table. How to read the above xml and insert into these two tables? Thanks [/INST]Check an example: declare @Activity table (id int not null primary key, Start datetime, Quantity int) declare @Observation table( activity_id int, Code int, Value int ) declare @example varchar(max) =' <Activity> <ID>2</ID> <Start>01/01/2012 13:00</Start> <Quantity>1</Quantity> <Observation> <Code>14</Code> <Value>5</Value> </Observation> <Observation> <Code>76</Code> <Value>5</Value> </Observation> </Activity> <Activity> <ID>3</ID> <Start>01/01/2012 14:00</Start> <Quantity>1</Quantity> <Observation> <Code>14</Code> <Value>10</Value> </Observation> </Activity> <Activity> <ID>4</ID> <Start>01/01/2012 15:00</Start> <Quantity>1</Quantity> </Activity>' declare @xml xml = cast(@example as xml) insert @Activity (id, Start, Quantity) select a.value('ID[1]', 'int'), a.value('Start[1]', 'datetime'), a.value('Quantity[1]', 'int') from @xml.nodes('/Activity') t(a) insert @Observation (activity_id, Code, Value) select o.value('../ID[1]', 'int'), o.value('Code[1]', 'int'), o.value('Value[1]', 'int') from @xml.nodes('/Activity/Observation') t(o) select * from @Activity select * from @Observation</s>
<s>[INST]size of data in field Hello, I have some fields and the length is 1,333 of these fields. The application team want to reduce the size of these fields and want to know how much data is stored in these fields so to decide how much they can reduce the field size without loosing the data. How we can check the size till the data is stored in these columns? Thanks[/INST]In case of characters, a query like this: select max(len(column1)) MaxLength, sum(len(column1)) TotalLength from MyTable will give the longest value (in characters) which is stored in *column1*. It also shows the total occupied space. Then the Application Team can decide if it has sense to reduce the size of the column.</s>
<s>[INST]Find what was causing blocking issues yesterday Hi, I have a job which occasionally runs slow. Is there a way in which I can find out what blocking occurred in the DB at a point in time? Thanks :)[/INST]There is nothing built into SQL Server to track that information. You can only see current blocking.</s>
<s>[INST]Growth Rate Experts, Need help to capture the growth rate for multiple database for the last 6-12 months for future projections. Is there a query for it. [/INST]Need help to capture the growth rate for multiple database You surely backup all databases and so you can get the required information from the backup history. -- Transact-SQL script to analyse the database size growth using backup history. DECLARE @endDate datetime, @months smallint; SET @endDate = GetDate(); -- Include in the statistic all backups from today SET @months = 12; -- back to the last 6 months. ;WITH HIST AS (SELECT BS.database_name AS DatabaseName ,YEAR(BS.backup_start_date) * 100 + MONTH(BS.backup_start_date) AS YearMonth ,CONVERT(numeric(10, 1), MIN(BF.file_size / 1048576.0)) AS MinSizeMB ,CONVERT(numeric(10, 1), MAX(BF.file_size / 1048576.0)) AS MaxSizeMB ,CONVERT(numeric(10, 1), AVG(BF.file_size / 1048576.0)) AS AvgSizeMB FROM msdb.dbo.backupset as BS INNER JOIN msdb.dbo.backupfile AS BF ON BS.backup_set_id = BF.backup_set_id WHERE NOT BS.database_name IN ('master', 'msdb', 'model', 'tempdb') AND BF.file_type = 'D' AND BS.backup_start_date BETWEEN DATEADD(mm, - @months, @endDate) AND @endDate GROUP BY BS.database_name ,YEAR(BS.backup_start_date) ,MONTH(BS.backup_start_date)) SELECT MAIN.DatabaseName ,MAIN.YearMonth ,MAIN.MinSizeMB ,MAIN.MaxSizeMB ,MAIN.AvgSizeMB ,MAIN.AvgSizeMB - (SELECT TOP 1 SUB.AvgSizeMB FROM HIST AS SUB WHERE SUB.DatabaseName = MAIN.DatabaseName AND SUB.YearMonth < MAIN.YearMonth ORDER BY SUB.YearMonth DESC) AS GrowthMB FROM HIST AS MAIN ORDER BY MAIN.DatabaseName</s>
<s>[INST]SQL Group By & Order By Hi In my SQL Stored Procedure, i have a column named 'seq' to force the correct order sequence for the return list. Within the data are 7 categories of data and for each category, the sequence is 1 to nth. I have a Where clause to show only active rows and also to capture the incoming parameter. If the parameter has a value, filter the data to that value. If the parameter IS NULL, return all data Group By a column. SELECT dbo.TBL_FinishList.prod_number, dbo.TBL_FinishList.alias AS description, dbo.TBL_FinishList.supplier_number, dbo.tbl_FinishGrade.FinishType AS finish_type, dbo.TBL_FinishList.TypeID FROM dbo.TBL_FinishList INNER JOIN dbo.tbl_FinishGrade ON dbo.TBL_FinishList.gradeID = dbo.tbl_FinishGrade.ID INNER JOIN dbo.tbl_FinishType ON dbo.TBL_FinishList.TypeID = dbo.tbl_FinishType.id LEFT OUTER JOIN dbo.tbl_FinishCategory ON dbo.TBL_FinishList.categoryID = dbo.tbl_FinishCategory.ID WHERE (dbo.TBL_FinishList.TypeID <> 0 AND TypeID = @TypeID OR @TypeID IS NULL AND (dbo.TBL_FinishList.active = '1')) GROUP BY dbo.TBL_FinishList.TypeID ORDER BY dbo.TBL_FinishList.seq This doesnt work when adding Group By and i get a naggregate error so what am i doing wrong? Id like the data list (when all is returned) to be grouped by the dbo.tbl_FinishType column so that when i see the data, all FinishTypes are together and in sequence.. How could i change my statement to achieve that? Thanks Nacho [/INST]Group by divides the query result into groups of rows, usually for the purpose of performing one or more aggregations on each group. If you use GROUP BY without aggregation, all fields after GROUP BY must appear in the SELECT list. You do not use aggregation in your code. At this time, all the fields after the SELECT must appear in the GROUP BY clause. Otherwise it will return the error you got. I guess what you want is: SELECT dbo.TBL_FinishList.prod_number, dbo.TBL_FinishList.alias AS description, dbo.TBL_FinishList.supplier_number, dbo.tbl_FinishGrade.FinishType AS finish_type, dbo.TBL_FinishList.TypeID FROM dbo.TBL_FinishList INNER JOIN dbo.tbl_FinishGrade ON dbo.TBL_FinishList.gradeID = dbo.tbl_FinishGrade.ID INNER JOIN dbo.tbl_FinishType ON dbo.TBL_FinishList.TypeID = dbo.tbl_FinishType.id LEFT OUTER JOIN dbo.tbl_FinishCategory ON dbo.TBL_FinishList.categoryID = dbo.tbl_FinishCategory.ID WHERE (dbo.TBL_FinishList.TypeID <> 0 AND TypeID = @TypeID OR @TypeID IS NULL AND (dbo.TBL_FinishList.active = '1')) ORDER BY dbo.TBL_FinishList.TypeID,dbo.TBL_FinishList.seq If this does not solve your problem, please provide a minimal example of the output you want.</s>
<s>[INST]when run this query get error invalid object x ? I run recursive but i face error it give me invalid object x so How to solve issue SELECT * INTO extractreports.dbo.getfinalpcMasks FROM (SELECT Po.FamilyId, Po2.GroupId, CONCAT( Po.PortionKey, Po2.PortionKey ) PortionKey , CONCAT(PNK.PortionKey , PNK.PortionKey) PartNumber FROM extractreports.dbo.GetFinalResultParts Po WITH(NOLOCK) INNER JOIN extractreports.dbo.GetFinalResultParts Po2 WITH(NOLOCK) ON Po.GlobalPnId = Po2.GlobalPnId AND Po2.GroupId = 2 INNER JOIN extractreports.dbo.GetFinalResultMasks PNK WITH(NOLOCK) ON Po.GlobalPnId = PNK.GlobalPnId AND PNK.GroupId = 2 AND Po.GroupId = 1 UNION ALL SELECT t.FamilyId, Po2.GroupId, CONCAT(t.PortionKey , Po2.PortionKey) PortionKey , CONCAT(t.PortionKey,PNK.PortionKey ) PartNumber FROM x t with(nolock) INNER JOIN extractreports.dbo.GetFinalResultParts Po2 WITH(NOLOCK) ON Po2.GlobalPnId = t.GlobalPnId AND Po2.GroupId = t.GroupId+ 1 INNER JOIN extractreports.dbo.GetFinalResultMasks PNK WITH(NOLOCK) ON PNK.GlobalPnId = t.GlobalPnId AND PNK.GroupId = t.GroupId+ 1 ) x so how to solve issue please ? [/INST]It is difficult to say how to solve the issue, since I have no idea of what you want to achieve. Of course one way get rid of the error message is to create a table x with the columns you have in the query. Then at least the query would compile. I note that you use x as an alias for the UNION ALL query. Maybe you intended to be something recursive. In that case, this might be the query WITH x AS ( SELECT Po.FamilyId, Po2.GroupId, CONCAT( Po.PortionKey, Po2.PortionKey) AS PortionKey, CONCAT(PNK.PortionKey, PNK.PortionKey) AS PartNumber FROM extractreports.dbo.GetFinalResultParts Po WITH(NOLOCK) INNER JOIN extractreports.dbo.GetFinalResultParts Po2 WITH(NOLOCK) ON Po.GlobalPnId = Po2.GlobalPnId AND Po2.GroupId = 2 INNER JOIN extractreports.dbo.GetFinalResultMasks PNK WITH(NOLOCK) ON Po.GlobalPnId = PNK.GlobalPnId AND PNK.GroupId = 2 AND Po.GroupId = 1 UNION ALL SELECT t.FamilyId, Po2.GroupId, CONCAT(t.PortionKey, Po2.PortionKey) AS PortionKey, CONCAT(t.PortionKey,PNK.PortionKey ) AS PartNumber FROM x t with(nolock) INNER JOIN extractreports.dbo.GetFinalResultParts Po2 WITH(NOLOCK) ON Po2.GlobalPnId = t.GlobalPnId AND Po2.GroupId = t.GroupId+ 1 INNER JOIN extractreports.dbo.GetFinalResultMasks PNK WITH(NOLOCK) ON PNK.GlobalPnId = t.GlobalPnId AND PNK.GroupId = t.GroupId+ 1 ) SELECT * INTO extractreports.dbo.getfinalpcMasks FROM x But this is a complete speculation on my side.</s>
<s>[INST]what condition case when related to portion key mean ? I work on sql server 2012 I don't understand condition below do this condition as below case WHEN Po.PortionKey LIKE '%\[\_\]%' THEN SUBSTRING(Po.PortionKey, LEN(LTRIM(RTRIM(Po.PortionKey)))+1,LEN(LTRIM(RTRIM(Po.PortionKey)))) end as modifiedportionkey what condition above mean can please give me sample [/INST]Why don't you ask the person who wrote it (which I assume is yourself) what the intention is? My reading is that if the PortionKey contains an underscore, return the empty string, else NULL. Although, this is somewhat simplified. If PortionKey would have some leading spaces, you could actually get back some non-blank characters. Since I don't know the business rules, I can't say whether this is correct or not. But I will have to admin that is seems nonsensical to me.</s>
<s>[INST]SQL :Select unique/distinct rows based on the other column. Hi Team - I am trying to return the rows below the scenario SQL 2017: create table TableK ( oldID int, newid int, oldname varchar(20), newname varchar(20), oldstreet varchar(20), newstreet varchar(20), lastupdatedt datetime ) insert into TableK values (1619,1619,'Eva','Zia','Broadst','lombardst','02/10/2021 13:57:00'), (1619,1619,'Eva','Zia','Broadst','lombardst','02/10/2021 14:57:00'), (1619,1619,' ','Zia','Broadst','lombardst','02/11/2021 14:57:00'), (1619,1619,'Ava','Zia','Broadst','lombardst','02/12/2021 13:57:00'), Below in my select statement below its returning all the 4 rows but if you look at the first two rows there is not change in actual values (id,name and street) so i want to select only one row with latest updated date. So i want to display only below three records : First row should be eliminated as its not the latesttime. (1619,1619,'Eva','Zia','Broadst','lombardst','02/10/2021 14:57:00'), (1619,1619,' ','Zia','Broadst','lombardst','02/11/2021 14:57:00'), (1619,1619,'Ava','Zia','Broadst','lombardst','02/12/2021 13:57:00'), Select distinct * from TableK Where oldid<>newid or oldname<>newname or oldstreet<>newstreet How do i write my select query ? Thanks[/INST], According to your requirement, you could try with **max(lastupdatedt ) ... group by...** as below: Select oldID,newid,oldname,newname,oldstreet,newstreet ,max(lastupdatedt) lastupdatedt from TableK group by oldID,newid,oldname,newname,oldstreet,newstreet Output : oldID newid oldname newname oldstreet newstreet lastupdatedt 1619 1619 Zia Broadst lombardst 2021-02-11 14:57:00.000 1619 1619 Ava Zia Broadst lombardst 2021-02-12 13:57:00.000 1619 1619 Eva Zia Broadst lombardst 2021-02-10 14:57:00.000 If above query is not working, please provide more sample data and expected output.</s>
<s>[INST]two digits after decimal ? I want two digits after decimal. cast(B.Bweight as decimal(10,2))/cast(C.iWeight as decimal(10,2))*100 [Percentage] currently i am getting below result 0.9021512838300 but i want 0.90[/INST]The resulting data type when you perform an operation on two decimal values is a complicated story, and I don't remember the rules by hart. But as you have experienced, dividing two `decimal(10,2)` values does not result in a new `decimal(10,2)` value. I would write this as cast( cast(B.Bweight as float)/cast(C.iWeight as float)*100 as decimal(10,2)) AS [Percentage] The reason I would cast to `float` before the division is that this the best accuracy for the division as such. But depending on the actual data types of the Weight columns, this may be an over kill. The important is that you need to cast the final result to `decimal(10,2)`.</s>
<s>[INST]Need to insert differences between Staging and Working tables into the Working Table Hi, Still kind of a newbie to SQL Server. Anyway I have two tables: tblStaging and tblWorking. The staging table is updated every 15 minutes and I need to look at what's different in the Staging table and insert the differences into the Working table. I have a combination of two fields that guarantee uniqueness. I also need to go the other way and look at what's in the Working table, that's not in the Staging table and delete those records from the Working table. Sorry for the wordiness. Just wanted to make things clear...[/INST]You can work from this pattern: MERGE tblWorking W USING tblStaging S ON W.keycol1 = S.keycol1 AND W.keycol2 = S.keycol2 WHEN NOT MATCHED BY TARGET THEN INSERT (keycol1, keycol2, othercol1, othercol2, ...) VALUES(S.keycol1, S.keycol2, S.othercol1, othercol2, ...) WHEN MATCHED AND NOT EXISTS (SELECT W.* INTERSECT SELECT S.*) THEN UPDATE SET othercol1 = S.othercol1, othercol2 = S.othercol2, WHEN NOT MATCHED BY SOURCE THEN DELETE ; The EXISTS clause for the WHEN MATCHED branch serves to filter out rows where nothing has changed. The use of INTERSECT has two purposes. The main advantage is that this takes care of that a column changes to and from NULL; this is a lot more messy if you use `=`. A second advantage is that you don't have to list all columns and just say `W.*` and `S.*`. However, this only works if you want to compare exactly every column. Sometimes there auditing or timestamp columns that are to be excluded from the comparison. In such case, there is no choice but to list all columns.</s>
<s>[INST]Nvarchar(Max) xml data into local drive Hi, I have a table with nvarchar(max) column where i have store the xml data. I want to export this nvarchar(max) xml data into my local drive. how to achieve that? Thanks [/INST]SSMS has so called **SQLCMD Mode**. It allows to output result of a query to a local file system. **SQL** -- To switch to SQLCMD Mode - select Query from the menu and then select SQLCMD Mode. :out e:\Temp\outputFileName.xml SET NOCOUNT ON; SELECT TOP(10) [CurrencyCode] ,[Name] ,[ModifiedDate] FROM [AdventureWorks].[Sales].[Currency] FOR XML PATH('row'), TYPE, ROOT('root');</s>
<s>[INST]Performance issue Experts , If I have a SQL Server 2019 having high physical reads , can it be said that it is a performance issue or do we need to look into some other parameters[/INST]As Erland mentioned, did any one complaint SQL server performance issue? If not, you do not have performance issue. The I/O from an instance of SQL Server is divided into logical and physical I/O. A logical read occurs every time the database engine requests a page from the buffer cache. If the page is not currently in the buffer cache, a physical read is then performed to read the page into the buffer cache. If the page is currently in the cache, no physical read is generated; the buffer cache simply uses the page already in memory. If you find performance problems when tuning a single statement and only appear when there is physical I/O, then there are a few things you need to do. **(1) Check whether the production server has a memory bottleneck, and whether there is a phenomenon of frequent page changes.** If there is no memory bottleneck in the production environment, or there are few Page Out/Page In actions, it means that SQL Server can maintain data pages in memory, and the performance problems you see are unlikely to occur, so there is no need to go too far. concern. If there is an obvious memory bottleneck, the first thing to solve is the memory bottleneck at the SQL Server server level, because this bottleneck will not only cause this statement to run slowly, but also affect the performance of other statements. **(2) Check whether this statement and the data it accesses is used frequently or occasionally.** If the problem statement is often called by different users, then the data it accesses should be cached in memory. If this sentence is only occasionally called by a specific user or task, and the amount of data it accesses is large and other people do not use it frequently, then it is normal for SQL Server not to put them in memory. For this Statement, it is reasonable to have physical I/O time in its running time. This may involve communicating with end users, setting their reasonable performance expectations, and arranging them to run during non-business peak hours, so as not to affect other key businesses. **(3) Check whether the statement execution plan can reduce the amount of data accessed.** The smaller the amount of data accessed by the statement, the less physical I/O to be done, and of course the faster it can be. From this perspective, it is also useful to tune the statement itself. **(4) Check the performance of the disk subsystem.** If the data accessed by the statement is probably not in the memory, and its amount is large, and its performance must be improved, the only way out is to improve the performance of the disk subsystem. In this case, the internal settings of SQL Server may help Nothing is busy, the work to be done may be more at the hardware level.</s>
<s>[INST]FCI Alignment Experts, A Generalized question , if I have a 2 node cluster with FCI instances active on both nodes , one active instance on each node. 8 cores 156 GB on each node. 64 GB aligned to each instance on their respective nodes. From memory perspective I understand total I will be using 128(64+64) GB if both Instances failover to one node. However just on a general basis if the CPU utilization is 40% on each node , when both the Instances failover to one node , am I liable to get performance issues. There are no performance issues when instances on their indusial nodes. Just wanted to understand if there could performance issues due to failover on one node on a high level , though I understand there could be various other factors also. [/INST]There could be performance issues - but if both instances never go above 40% utilization then I wouldn't think performance will suffer. With that said - I would be concerned because there are going to be times on each instance where they spike to 60%+ which can and will affect the other instance.</s>
<s>[INST]AlwaysOn Replication Experts , For a read-only / read intent database in secondary alwayson , can we have a sync replication and automatic failover between primary and secondary or will it be async only with a manual failover[/INST]\> but does it lead to a lot of locking due to sync replication for the read requests No. > \> Also with node1\sql2019 being primary, will the replication be from node1\sql2019 -\> node3\SQL2019 or can it be from node2\sql2019 -\> node3\SQL2019 also The data replication is from node1\sql2019 -\> node3\SQL2019. The replication is from primary replica to secondary replica.</s>
<s>[INST]Update trigger is not updating row? I am inserting row in table(#tbl_leaves_Detail) using trigger,now i want to update it ,but update trigger is not working CREATE TABLE Tbl_Leaves ( L_ID int, L_From_Date date, L_To_Date date, L_Days int ); CREATE TABLE Tbl_Leaves_Details ( ID int IDENTITY(1, 1) NOT NULL, L_ID int, L_Date date, L_Qty int ); GO CREATE TRIGGER TI_Tbl_Leaves ON Tbl_Leaves AFTER INSERT AS BEGIN ;WITH CTE AS ( SELECT L_ID, L_From_Date, L_To_Date FROM inserted UNION ALL SELECT L_ID, DATEADD(day, 1, L_From_Date) AS L_From_Date, L_To_Date FROM CTE WHERE L_From_Date < L_To_Date ) INSERT INTO Tbl_Leaves_Details SELECT ID,L_ID, L_From_Date, 1 AS L_Qty FROM CTE; END GO INSERT INTO Tbl_Leaves VALUES (1001, '2021-06-01', '2021-06-05', 5); GO SELECT * FROM Tbl_Leaves; SELECT * FROM Tbl_Leaves_Details; GO Below is Update trigger which is not updating rows in #tbl_Leaves_Detail, alter TRIGGER [dbo].[TI_Tbl_Leaves_Update] ON [dbo].[tbl_Leaves] AFTER Update AS BEGIN ;WITH CTE AS ( SELECT L_ID, L_From_Date, L_To_Date FROM Updated UNION ALL SELECT L_ID, DATEADD(day, 1, L_From_Date) AS L_From_Date, L_To_Date FROM CTE WHERE L_From_Date < L_To_Date ) Update tbl_Leaves set L_From_Date='2021-06-01',L_To_Date='2021-06-02', L_Days=2 where L_ID=1 END it i will two row and remaing row ,need to be deleted. [/INST]You could also modify the update trigger like below: CREATE TRIGGER [dbo].[TI_Tbl_Leaves_Update] ON [dbo].[tbl_Leaves] AFTER Update AS BEGIN DELETE M FROM [dbo].Tbl_Leaves_Details M INNER JOIN Inserted I ON I.L_ID = M.L_ID; ;WITH CTE AS ( SELECT L_ID, L_From_Date, L_To_Date FROM inserted UNION ALL SELECT L_ID, DATEADD(day, 1, L_From_Date) AS L_From_Date, L_To_Date FROM CTE WHERE L_From_Date < L_To_Date ) INSERT INTO Tbl_Leaves_Details(L_ID,L_Date,L_Qty) SELECT L_ID, L_From_Date, 1 AS L_Qty FROM CTE; END</s>
<s>[INST]Code line limitation in Stored Procedures Hi, I have a more generic Question about Stored Procedures. Is there a limitation of Code Lines in a SP, to create a optimized Execution Plan? Lets say in case that a SP has more than 1000 Code lines (excluding Comments and other non relevant lines) is it possible that the optimizer can not run proper and create a not or less optimized execution plan? Kind regards[/INST]The largest proc I heard about had 70,000 lines of code - and that was almost 20 years ago. The DML statements in the proc are optimized per statement. I.e., possible optimization restrictions isn't dependent on proc size, but rather on each statement complexity.</s>
<s>[INST]Memory Errors in SSMS log Hello , I have 1 database server which has 32 GB physical memory . 4 cpu. Instance is running SQL Server 2014 version, and OS is Windows Server 2016. Right now, 8 gb is allocated to SQL Server, and remaining is for OS. Before I have adjusted to16 gb is given to SQL and remaining to OS. We have an external application which connects to the DB, it will work fine for few days, and then the next time they try to login, it wont allow from application. We see these errors in log file, and then I end up restarting SQL services. Then again it will be fine for few days, and then same issue will repeat. Please help! There is insufficient system memory in resource pool 'internal' to run this query. Error: 17300, Severity: 16, State: 1. (Params:). The error is printed in terse mode because there was error during formatting. Tracing, ETW, notifications etc are skipped. Failed to reserve pages: FAIL_PAGE_RESERVATION 128 [/INST]Failed to reserve pages: FAIL_PAGE_RESERVATION 128 You are facing OOM issue and primarily it seems due to low memory set for SQL Server. As Amelia has suggested you should increase the max server memory. SQL Server is even not able to reserve memory, forget about allocating. > Right now, 8 gb is allocated to SQL Server, and remaining is for OS. This does not seems correct and this could be the reason for OOM error. You have 32 GB and giving just 8 GB to SQL Server will starve it for memory and you may see such issues. If nothing else is running on the system set max server memory to 26 or 27 GB.</s>
<s>[INST]SQL Startup Experts , During the SQL Server startup the database recovery happens , is it simultaneous for all the databases on the Instance or is sequential i.e only when one database recovery completes does the next one starts Recovery completed for database xxx(database ID 25) in 2 second(s) (analysis 50 ms, redo 0 ms, undo 1005 ms.) This is an informational message only. No user action is required. Does it impact the coming up of the SQL Instance [/INST]I seem to recall that I saw a discussion on this some time back. If memory serves, the recovery is parallel for the n databases with the lowest database_id, and then it is serial for the rest. But my memory is foggy here, so I am not sure that is wholly correct. What I am certain of is that all there is some amount of parallelism, but if you have 3000 databases on the instance, it is not going to recover all 3000 in parallel, but nor one by one. And the order is largely controlled by the database_id.</s>
<s>[INST]SQL Server after version 2019 While it seems clear Microsoft has its head up the clouds so far that it may never see us little people back down here on planet Earth (you know, us on-prem guys that MS no longer cares about), I was wondering - and perhaps having hope against all hope---- Has there been any mention of the next version of SQL Server? SQL Server 2022, perhaps? JamesNT[/INST]Nothing as yet, but the normal cadence is usually every couple of years. Be assured that Microsoft hasn't forgotten on-premises (and of course VM-based) SQL Server users - I'm sure the license sales there count just as much as subscriptions in Azure :-) I'm sure you will see a flurry of activity when the early beta versions get dropped and are available for testing.</s>
<s>[INST]Connect to SQL database on server Hi all, I am new with android coding with Visual Studio 2019. Please help to show me or give me a sample code like input username/password and click "Sign in" button, the app will check user/pass in SQL login table to process. Thanks a lot.[/INST]I think you may need to ask this question in the vs or android forums(by adding related tags). The question is more about how to write code. The tag: sql-server-general indicates that this is a forum for SQL Server technical issues.</s>
<s>[INST]Remove records from a table that are in another table Hi, I have a table (CTL_Sup) which has 25k records all with a Cust_ID I have another table (Cont_all) which has 450k records all with a Cust_ID Within the Cont_all table, we have the 25k records included that are in the CTL_Sup and what I want to do, is remove these 25k accounts from the Cont_all table Any idea how I would write a query to do this please? I hope this makes sense, [/INST]Consider three of possible approaches: delete from a from Cont_all a inner join CTL_Sup s on s.Cust_ID = a.Cust_ID or delete from a from Cont_all a where exists (select * from CTL_Sup where Cust_ID = a.Cust_ID) or delete from Cont_all where Cust_ID in (select Cust_ID from CTL_Sup)</s>
<s>[INST]How to do change tracking for data insert/update & delete some time dotnet application change data in a specific table or some time user change data from SSMS. how could i detect which application made the change and from which IP data has been changed. please guide me full steps to achieve this. thanks[/INST]DECLARE @retTable TABLE ( SPID int not null , Status varchar (255) not null , Login varchar (255) not null , HostName varchar (255) not null , BlkBy varchar(10) not null , DBName varchar (255) null , Command varchar (255) not null , CPUTime int not null , DiskIO int not null , LastBatch varchar (255) not null , ProgramName varchar (255) null , SPID2 int not null , REQUESTID INT ) INSERT INTO @retTable EXEC sp_who2 SELECT Status, Login, HostName, DBName, Command, CPUTime, ProgramName -- * FROM @retTable --WHERE Login not like 'sa%' -- if not interested in sa ORDER BY Login, HostName</s>
<s>[INST]Identify cause of "Operand type clash: text is incompatible with bit” I have 2 SQLExpress tables Properties & PropertiesHistory, stored locally on my machine. They are meant to have the same structure because Properties History is an archive of changes to Properties records taken whenever a change to a Properties record is made. The SQL to do this is INSERT into PropertiesHistory SELECT * FROM Properties WHERE ID = nnn ( nnn is the id of the current record) . This throws the error “Operand type clash: text is incompatible with bit” This code works for other developers with their local copies of the of the database, so I think the problem is with the structure of the 2 tables on my machine. I have run the query select * from information_schema.columns where table_name = 'Properties' union select * from information_schema.columns where table_name = 'PropertiesHistory' order by COLUMN_NAME This confirmed that the bit fields are both defined as such in the source & destination tables, as are the other fields. I have tried changing the SQL syntax to the following variants with no joy INSERT PropertiesHistory SELECT * FROM Properties WHERE ID = nnn ( same error ) INSERT into PropertiesHistory SELECT Field1,field2,field,…field99 FROM Properties WHERE ID = nnn ( full list of fieldnames – same error again) I tried cutting this fieldname list down to identify the problem field, but this objected with Column name or number of supplied values does not match table definition. [/INST]It is recommended to provide the DDL of both tables so that we could check further. Totally agreed with other experts, please have a try to list the columns one by one and keep the same order in both tables in the insert statement. > This throws the error “Operand type clash: text is incompatible with bit” What is your version of SQL Server? Actually the **text** datatype will be removed in a future version of SQL Server. Please consider to use **char** or **varchar(max)** instead of text or upgrade your SQL server. You could also try to cast the value from TEXT to CHAR right now and then the SQL Server will implicitly convert it to BIT.</s>
<s>[INST]Starting up databases after SQL Service restart Hello, I have a SQL instance which contains 74 databases. So I had to restart the SQL Service about 1 hour and 15 minutes ago. Ever since then the SQL log is flooded with these messages. Starting up database 'DB1' Starting up database 'DB1' Starting up database 'DB2' Starting up database 'DB3' Starting up database 'DB1' Starting up database 'DB1' Starting up database 'DB2' Starting up database 'DB3' etc..... I see multiple attempts and multiple SPIDs for 1 database.... Why is this happening? Should the starting up of databases be quick and then the messages should stop flooding the log ? [/INST]When I searched for such information, I found that some cases points to the AUTO_CLOSE option of the database, this option is set to True. Please check your database settings. Also, if this is not the cause, please tell me the specific version of SQL Server so that I can try to reproduce your problem in a test environment to find the possible cause.</s>
<s>[INST]TempDB and Memory Fellow DBA's, I am not necessarily having a serious ongoing issue but am trying to understand what I saw. I was reviewing who was using memory across all dbs. SQL 2016 had max mem set to 32 gb. Of that, tempdb was taking about 60-70%. There were no queries running. version store is not running. I have tempdb broken across 8 files. Each was setup exactly as planned. Each has grown very close to each other. Each was about 5600 mb each. My below scrips indicate that about 18 gb of that sql memory space is unallocated to tempdb by looking at allocation units not tied to buffer descriptors. SELECT Unallocated_MB = COUNT(1)/128 FROM sys.dm_os_buffer_descriptors bd LEFT JOIN sys.allocation_units au ON bd.allocation_unit_id = au.allocation_unit_id WHERE bd.database_id = 2 AND au.allocation_unit_id IS NULL 1 - How could tempdb still have buffers tied it for hours? I would have thought it would have released most of the 18gb? Or am I reading/interpreting this wrong? thx MG [/INST]It is completely normal and desirable for the buffer to contain pages for a long time. Once SQL Server allocates RAM, it never releases it, unless the OS signals low memory. This is completely normal and expected and desirable behavior and does not in any way indicate an issue.</s>
<s>[INST]Correct way to disable login for SA account?? We need SA to be database owner but reduce potential security issues. I've been told one thing to do is to *disable the login permission for the SA account*. However, in looking this up I'm confused...everything is t-sql code and it's not clear whether to use deny or revoke... Is it possible to do this in SSMS and if so how?? Thank you, Tom [/INST]There are two ways to disable the "sa" account. One way, in SSMS, is to right click on the login and select properties>status>Login: disabled. Another way is via t-sql, with this command: "Alter Login [sa] disable". The sa account can still own the databases but yet still be disabled.</s>
<s>[INST]Can you install MS SQL SVR Express 2019 on Windows SVR 2016 that already has SQL SVR 2012 Native Client and SQL SVR Compact 3.5 SP2 installed Hi, I am trying to see if it is OK to install MS SQL SVR Express 2019 on a Windows 2016 Standard server that already has SQL Server 2012 Native Client and SQL Server Compact 3.5 SP2 ENU installed. I know it is generally OK to install and use different instances but cannot find anything stating it is OK to have all three of these installed on the same server. Please let me know if you need anything else for this. Thank you.[/INST]Yes. They are completely independent.</s>
<s>[INST]SQL Agent Job Step Hangs and not fail Good day, I have a ssis package within an SQL Agent Job, 2 things that fails on this pkg 1. Oracle connection, continously tries to reconnect and not fail 2. second part imports the oracle data within sql tables Part1 would not find a connection and will run forever, second part also does not fail Is there a way to set timer limit on pkg step to rather fail and email/sms me. Management not happy, i rather want it to fail stop Job and restart job after an hour I tried the advanced retry intervals but it doesnt retry, its like there's no connection or sql db is locked and it hangs Please any deas! Regards [/INST]there is no provision in Agent to set a timeout for a job. You would have to set up a parallel job that monitors this one and kills is it, if it runs too long. But that does not seem to be correct solution. Rather you would handle that in your SSIS package. To that end, you should add the tag for sql-server-integration-services, so that you address people who know SSIS. (I don't.)</s>
<s>[INST]Transactional log full in production db The Transactional log is full in production environment. I want to create a new transactional log in another disk say :M for temporary purpose as my current log file :L Drive is full. What do I do to clear the transactional log file in L Drive. How do i delete the new log file as it is temporary Log file. I want to keep only one transactional file at L Drive only. What are the steps for the backup of so that i don't mess up with the transactional log LSN.[/INST]First check the column log_reuse_wait_desc in sys.databases for the database. If this is LOG_BACKUP, backup the transaction log and you should be fine. If it is something else, you can add that extra log file, but you need to sort the reason why the log will not be truncated. Once you have cleared up the reason why the log does not truncate, you can drop that extra log file. However, this requires that the active portion of the log is solely in L. There is not much problem with the LSN. The log is like a ring buffer, and if you add another file, that second log file becomes part of that ring buffer.</s>
<s>[INST]Date Function Create a field in Table Colum:- tbl_inst_install_date Data Type -----varchar(50) Date **03/02/2016** No, I want to Convert this Colum Date from 03/02/2016 to **2016** (dd/mm/yyyy) To (YYYY) Kindly Advise us [/INST]Please refer below: select year(cast(yourcolumn as date)) from yourtable select format(cast(yourcolumn as date),'yyyy') from yourtable select right(yourcolumn,4) from yourtable</s>
<s>[INST]Set session to be case sensitive Is it possible to set the collation for a query so that everything is case sensitive?[/INST]If your database and columns use a case-insensitive collation, you cannot specify/force case-sensitive comparison at the session/query level. However, you can do so with a COLLATE clause on query predicates. For example, with case-insensitive column collation Latin1_General_CI_AS: --case-insensitive will return 'Shaw', 'SHAW', 'shaw', etc. SELECT * FROM dbo.Employee WHERE LastName = 'Shaw'; --case-sensitive will return only 'Shaw' SELECT * FROM dbo.Employee WHERE LastName = 'Shaw' COLLATE Latin1_General_CS_AS; Be aware that a COLLATE clause may preclude indexes from being used efficiently and result poor query performance. A way to coerce a case-sensitive compare and leverage indexes too is by including both case-insensitive and case-sensitive predicates. This will allow the index to be leveraged for the case-insensitive predicate and further limit rows with the case-sensitive criteria to further filter the desired rows. --case-sensitive will return only 'Shaw' and leverage indexes when appropriate SELECT * FROM dbo.Employee WHERE LastName = 'Shaw' AND LastName = 'Shaw' COLLATE Latin1_General_CS_AS; If all of your queries require case sensitivity, consider a case-sensitive collation (instance, database, and columns). Everything (including object names) will then be case-sensitive.</s>
<s>[INST]AlwaysOn Load Though it would depend on the load , however on a very high level is there any study which mentions how much % the CPU, memory consumption would increase on setting up 2 replicas sync and async.[/INST]\> however on a very high level is there any study which mentions how much % the CPU, memory consumption would increase on setting up 2 replicas sync and async. There is no MS official document mentioned this. But you can using performance monitor to monitor the values change for a instance.</s>
<s>[INST]OUTER APPLY performance Hi, I have an OUTER APPLY in my query. When I run the query without including the OUTER APPLY columns in the main SELECT the performance is good. For example, in following query I am not including any of the columns from X. SELECT U.UserID, U.FirstName FROM Users U OUTER APPLY (SELECT TOP 1 Salary, Currency, Interest FROM Salary S WHERE S.UserID = U.UserID AND S.PaymentDate = U.StartDate) X When I include even a single column from the OUTER APPLY the performance slows down. SELECT U.UserID, U.FirstName, X.Salary FROM Users U OUTER APPLY (SELECT TOP 1 Salary, Currency, Interest FROM Salary S WHERE S.UserID = U.UserID AND S.PaymentDate = U.StartDate) X Does anybody have an idea why this might be happening? Thanks, Ben [/INST]It slows down because it's actually having to do the work... the first query will be ignoring the calculation since it knows it has no impact on the output When you say "slows down", is it a significant slowdown? is that meant to be an "AND s.PaymentDate..."? Or is there some code missing? Are you expecting more than 1 record per user/payment date combination?</s>
<s>[INST]How to remove SQL Server Standared Instance and keep Express Edition ? Hi, We get both SQL Server 2012 Standard Edition and SQL Server 2012 Express installed on the same Windows Server. There is a request to get the SQL Server 2012 Standard Edition to be removed. From Programs, we find that there are a number of SQL Server related programs and don't know which one should be removed (without affecting the Express Edition). Is there any suggestion ? Thanks[/INST]In Control Panel->Program and Features, find the entry saying "Microsoft SQL Server 2012". Select it and select Uninstall/Change and in the mini-menu that comes up select Remove. This starts the Setup Wizard, and here you can select which instance to work with.</s>
<s>[INST]Executing SQL script from remote computer from command prompt We have Two Servers Server 1--\> Our APplication servers Server 2--\> MSSQL DB server this is a Training env setup so we restore it every week, There is a PowerShell script that does this restoration, The script stops/start services on "Server" then there is step for Drop and restoring DB which we are doing manually from MSSQL studio > \# copy golden volumes to current volume location # ***ROBOCOPY PARAMETERS*** # /mir - Mirrors a directory tree robocopy $VolumeSource $VolumeDestination /mir /v /s /b robocopy $Volume1Source $Volume1Destination /mir /v /s /b # Pop up box notifying user that the database needs to be restored. # Script can continue when user selects OK $Shell = New-Object -ComObject "WScript.Shell" $Button = $Shell.Popup("Continue only after the database has been restored", 0, "Restore Database", 0) # start only DB service to import the golden database # Start-Service $DBServices # Restore the database using the SQL file # Invoke-Sqlcmd -InputFile "C:\Users\serviceamefusn\Desktop\ServerRefresh\DBBak.sql" | Out-File -filePath "C:\Temp\RestoreLogSqlCmd.rpt" -verbose # Invoke-Sqlcmd -InputFile "C:\Users\serviceamefusn\Desktop\ServerRefresh\ClusterRestore.sql" | Out-File -filePath "C:\Temp\RestoreClusterLogSqlCmd.rpt" -verbose # loop through each service, if its stopped, start it foreach($ServiceName in $Services) { $arrService = Get-Service -Name $ServiceName \#write-host $ServiceName while ($arrService.Status -ne 'Running') { Start-Service $ServiceName write-host $ServiceName 'is currently' $arrService.status write-host $ServiceName' is Starting' Start-Sleep -seconds 20 $arrService.Refresh() Blockquote So the SQL scripts C:\Users\serviceamefusn\Desktop\ServerRefresh\DBBak.sql" and ClusterRestore.sql, currently exeuting as mannual method from MS-SQL mgmt studio Is there way we can do it directly from PowerShell script? so that One click will complete all required steps Thanks in Advance [/INST]So the SQL scripts C:\Users\serviceamefusn\Desktop\ServerRefresh\DBBak.sql" and ClusterRestore.sql, currently exeuting as mannual method from MS-SQL mgmt studio > Is there way we can do it directly from PowerShell script? so that One click will complete all required steps If I understand correctly, you are executing the PowerShell `Invoke-Sqlcmd` commands from an interactive SSMS PowerShell session on Server1 in the context of the Server2 target database server. Those same commands can be executed directly from any PowerShell session on Server1 but you need to specify the `-Server` argument in order to run the SQL scripts against the remote Server2 instance. You should be able to include these in your existing PowerShell script file:. Invoke-Sqlcmd -InputFile "C:\Users\serviceamefusn\Desktop\ServerRefresh\DBBak.sql" -Server "Server2" | Out-File -filePath "C:\Temp\RestoreLogSqlCmd.rpt" -verbose Invoke-Sqlcmd -InputFile "C:\Users\serviceamefusn\Desktop\ServerRefresh\ClusterRestore.sql" -Server "Server2" | Out-File -filePath "C:\Temp\RestoreClusterLogSqlCmd.rpt" -verbose</s>
<s>[INST]python to extract/manipulate text data DIRECTLY with MS SQL Currently I use basic SQL's string functions (PATINDEX and SUSTR) to extract text data. From what I understand, MS SQL does not have full implementation of regex which makes it very difficult to extract data from string. Some people suggested Python because it's more suited for text string manipulation. So my question has two parts: 1. Is there SQL capabilities that I am not aware of? I would prefer to stay native with SQL. 2. Is there SQL capabilities that I am not aware of? I would prefer to stay native with SQL. How easy or difficult is it to go with Python route? And can I read/write **directly** to SQL? [/INST]If you are on SQL 2017, you can use Python from within SQL Server. It is an optional install, though, so you may not have it. But you can re-run Setup to add it. Once you have it place, you need to run sp_configure 'external scripts enabled', 1 RECONFIGURE Here is a sample script where I use Python to remove all non-digits from a script: USE tempdb go CREATE TABLE testtabell(id int NOT NULL PRIMARY KEY, litetext varchar(20) NOT NULL) INSERT testtabell(id, litetext) VALUES(1, 'ABC7890DEF'), (2, '123 00 00'), (3, 'Ingasiffror'), (4, '1234567890') EXEC sp_execute_external_script @language = N'Python', @script = N'import re, pandas Ret = InputDataSet Ret["litetext"] = pandas.Series([re.sub("[^0-9]", "", i) for i in Ret["litetext"]]) ', @input_data_1 = N'SELECT id, litetext FROM testtabell', @output_data_1_name = N'Ret' WITH RESULT SETS ((id int, litetext varchar(10))) go</s>
<s>[INST]SQL Server 2019 Database scoped configuration are there any good link / demo/ example for the following SQL Server 2019 Database IDENTITY_CACHE ISOLATE_SECURITY_POLICY_CARDINALITY ACCELERATED_PLAN_FORCING GLOBAL_TEMPORARY_TABLE_AUTO_DROP VERBOSE_TRUNCATION_WARNINGS thanks[/INST]For GLOBAL_TEMPORARY_TABLE_AUTO_DROP option, you can try to create a global temporary table and not use it. By default (GLOBAL_TEMPORARY_TABLE_AUTO_DROP is on), the global temporary table will be deleted automatically. If you create a global temporary table when GLOBAL_TEMPORARY_TABLE_AUTO_DROP is off, the global temporary table needs to be deleted using the DROP TABLE statement, or it will be deleted when the server is restarted.</s>
<s>[INST]Why am I getting error 'Conversion failed when converting date and/or time from character string'? Seems like other people have already asked this question, but none of the answered helped with my situation. I have a couple of 'stored valued functions' that take a date as an argument. create function loss.ClaimsPolAsOf ( @cutoff datetime ) returns table as return select i.\*, d.groupCode as covGroup from loss.Claim AS c, loss.ClaimPolInfo AS i, admn.CoverageCode AS d where i.claimId = c.claimId and i.valueDate = ( select max(valueDate) from loss.ClaimInfo where claimId = c.claimId and valueDate \< @cutoff ) and d.covCode = c.covCode; go This first function above works fine, not issues at all. The next one is the one that is giving me problems. create function loss.PolicySummary ( @cutoff datetime ) returns @table table (polNo varchar(25), valueDate datetime, covGroup varchar(3), lossRunDate datetime, totalClaims int, CWP smallint, paidLosses decimal(18,2), LAE decimal(18,2), openClaims smallint, openReserves decimal(18,2), num_loss25to100k smallint, tot_loss25to100k decimal(18,2), num_loss100kPlus smallint, tot_loss100kPlus decimal(18,2)) as begin insert into @table select polNo, covGroup, max(valueDate) as lossRunDate, ( select max(valueDate) as valueDate from admn.PolicyRefresh where valueDate \<= @cutoff and polNo = c.polNo ), count(distinct(claimNo)) as totalClaims, SUM(CASE WHEN closed = 1 THEN CASE WHEN lossPaid = 0 THEN 1 ELSE 0 END ELSE 0 END) as CWP, SUM(lossPaid) as paidLosses, SUM(expPaid) as LAE, SUM(CASE WHEN closed=0 THEN 1 ELSE 0 END) as openClaims, SUM(CASE WHEN closed = 0 THEN lossReserve ELSE 0 END) + SUM(CASE WHEN closed = 0 THEN expReserve ELSE 0 END) as openReserves, SUM(CASE WHEN (lossPaid + lossReserve) BETWEEN 250 AND 999.99 THEN 1 ELSE 0 END) as num_loss250to1000, SUM(CASE WHEN (lossPaid + lossReserve) BETWEEN 250 AND 999.99 THEN (lossPaid + lossReserve) ELSE 0 END) as tot_loss250to1000, SUM(CASE WHEN (lossPaid + lossReserve) \>= 1000 THEN 1 ELSE 0 END) as num_loss1000Plus, SUM(CASE WHEN (lossPaid + lossReserve) \>= 1000 THEN (lossPaid + lossReserve) ELSE 0 END) as tot_loss1000Plus from loss.ClaimsPolAsOf(@cutoff) c group by polNo, covGroup return end go If I call the first function using a date for instance: select \* from loss.ClaimsPolAsOf('2020.02.01') I get the result that I was expecting and no errors. But when I use the same date on the second function: select \* from loss.PolicySummary('2020.02.01') I get the error 'Conversion failed when converting date and or/or time from character string'. Why is this happening, why does the date work fine for the first function (as well as other functions I've created) but not for the second function. It seems to be the only function that gives me issues and it's not just that specific date, it gives me an error with every date I enter. Thank you in advance for your help [/INST]Maybe change the order of values: insert into @table select polNo, ( select max(valueDate) as valueDate from admn.PolicyRefresh where valueDate <= @cutoff and polNo = c.polNo ), covGroup, max(valueDate) as lossRunDate, Also check the other columns and values.</s>
<s>[INST]Can I concatenate two database table fields having integer datatype?? > Blockquote Hello, I am creating a table and I would want two particular fields to concatenate to form a 3rd field. Take for instance: ------------------------------------------------------------------------ class int not null, studentNo int unique IDENTITY(100000,1) Primary Key, StudentCode... ------------------------------------------------------------------------ Class field will be 3-digits integer. StudentNo will be automatically generated, starting from 10,000 StudentCode (I want it to contain the class 3-digits for each student and also the studentNo. It will start with the 3-digits of the class. i.e to concatenate the class value and the studentNo value) I try as much to explain because I want explicit suggestion. If you are proficient with database (MySql or Microsoft Sql), and you know about this, then kindly help. Please help with a line or lines of codes. [/INST]Did you already try *concat(class, studentNo)*? (Assuming that *class* does not start with zeroes). The column can be defined like this:   *StudentCode as concat([class], studentNo)* It will be calculated automatically.</s>
<s>[INST]Will SSMS v18.4 supports SQL Server 2008, 2012? Hi, I would like to know the supported SQL Server versions with ssms 18.x Thanks [/INST]\>Will SSMS v18.4 supports SQL Server 2008, 2012? Yes, it is supported. Full agree with VaibhavChaudhari, SSMS 18.x works with all supported versions from SQL Server 2008 to SQL Server 2019 (15.x).</s>
<s>[INST]JSON query This should be super simple, but I cannot get this to work. I want to extract routes data along with the trail id. Here is what I have SET @jsonVariable = N'\[ { "id": 1, "image": "trails/1.jpg", "name": "Countryside Ramble", "route": [ { "stage": 1, "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit." }, { "stage": 2, "description": "Curabitur interdum molestie tempus." }]}, { "id": 2, "image": "trails/2.jpg", "name": "Woodland Walk", "route": [ { "stage": 1, "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit." }] }] I removed some irrelevant info for now. I tried different variations of the syntax and I am unable to get information the way I want (e.g. route stage and description and Id of the trail. Thanks in advance. [/INST]Assuming that you have SQL Server 2016 or later. **SQL** DECLARE @json NVARCHAR(MAX) = N'[ { "id": 1, "image": "trails/1.jpg", "name": "Countryside Ramble", "route": [ { "stage": 1, "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit." }, { "stage": 2, "description": "Curabitur interdum molestie tempus." } ] }, { "id": 2, "image": "trails/2.jpg", "name": "Woodland Walk", "route": [ { "stage": 1, "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit." } ] } ]'; SELECT JSON_VALUE(parent.value, '$.id') as id , JSON_VALUE(parent.value, '$.image') as [image] , JSON_VALUE(parent.value, '$.name') as [name] , JSON_VALUE(child.value, '$.stage') as stage , JSON_VALUE(child.value, '$.description') as [description] FROM OPENJSON(@json) AS parent CROSS APPLY OPENJSON(parent.value, '$.route') AS child;</s>
<s>[INST]SQL Server covering index I'm currently trying to optimize a number of indexes of an SQL Server OLTP database. I would like to shrink the number of indexes by either deleting them because they are of no use or combining those which have overlapping keys and or includes. One thing I'm not fully sure of is how a nonclustered index with multiple key columns is used if only a part of the index key is provided in a search predicate. Assume an index key like (IDCustomer, OrderDate) and an included column (OrderNumber). When a query like SELECT IDCustomer, OrderDate, OrderNumber FROM table WHERE IDCustomer = 123 gets fired ... is the index used event though there are not all of the key columns provided in the serach predicate or should I create a separate index for the IDCustomer column? And what if an order gets applied like SELECT IDCustomer, OrderDate, OrderNumber FROM table WHERE IDCustomer = 123 ORDER BY OrderDate Can I benefit from that index? Best Regards Johannes [/INST]A good way to understand whether an index is useful is that you imagine that you have the data written down on paper or a plain text file in the order given by the index, and then think of how you as a human would find data in that text. So if you have an index `(IDCustomer, OrderDate) INCLUDE OrderNumber` and you have the query: SELECT IDCustomer, OrderDate, OrderNumber FROM table WHERE IDCustomer = 123 That index is perfectly usable. And if you slap on `ORDER BY OrderDate`, the index is even better. But if you try the query SELECT IDCustomer, OrderDate, OrderNumber FROM table WHERE OrderDate = '20210707' SQL Server can no longer seek the index, since the rows with an OrderDate of July 7th are scattered all over the index. But since the index is covering, SQL Server will scan the index, but that will be from start to end. More generally, say that you have an index on (a, b, c, d, e), and a query that goes: SELECT ... FROM tbl WHERE a = @val1 AND b = @val2 AND d = @val3 AND e = @val4 SQL Server might use the index for this query, but it can only use (a, b) as seek predicates since c is absent in the WHERE clause. If you were to deal with this as a human, you may know that c can only be 0 or 1, so you would just read in two places of the list, but SQL Server does not have any rule for this, but resorts to scanning the entire range for (a,b).</s>
<s>[INST]Count - Over Partition and Case Hi, I have a variable 'DU_Type' with the outputs being a '1' and '0'. ('1' being Yes, '0' being No) I want to do a count, something like this, but can't quite get it to work and wondered if anyone can help please? count(case when b.DU_Type = '1' then '1' else '0' ) over (partition by a.product,b.DU_Type ) as DU_Type_Yes This count seems to count for both values (1 and 0). All I want is to show the total against 1 please. [/INST]Use sum() instead of count() and when using sum don't use quotation marks ('), like this: sum(case when b.DU_Type = '1' then 1 else 0 end) over (partition by a.product, b.DU_Type) as DU_Type_Yes The count() function counts all strings whether it is '0' or '1'</s>
<s>[INST]SQL Server 2019 Datacenter Editon ? Hi, Vendor says that our SQL Server is running Datacenter Edition that is not supported. However, I find that there are only Standard Edition and Enterprise Edition available for SQL Server 2019. Is it correct ? I also find out the version we are running Microsoft SQL Server 2019 (RTM-CU10) (KB5001090) - 15.0.4123.1 (X64) Mar 22 2021 18:10:24 Copyright (C) 2019 Microsoft Corporation Standard Edition (64-bit) on Windows Server 2019 Datacenter 10.0 \<X64\> (Build 17763: ) Thanks [/INST]**Standard Edition** (64-bit) on Windows Server 2019 **Datacenter** 10.0 <X64> (Build 17763: Your Windows Server OS is a Datacenter Edition, your SQL Server is a Standard Edition.</s>
<s>[INST]Tables in a particular SQL Server Filegroup ? Hi, We find that there the database used by our Network Monitoring Software makes use of a couple of File Groups. Is there any way to find out which tables are located in a particular File Group ? Thanks[/INST]The following query will return the results of the tables created by the user on different Filegroup in a particular database . use DB go SELECT distinct o.[name], o.[type], f.[name] FROM sys.indexes i INNER JOIN sys.filegroups f ON i.data_space_id = f.data_space_id INNER JOIN sys.all_objects o ON i.[object_id] = o.[object_id] AND o.type = 'U' -- User Created Tables</s>
<s>[INST]SQL Server 2017 CLR strict security May I know if I have such CLR in an old database , say for example SQL Server 2014 , I would like to do backup restore to SQL Server 2017 or SQL Server 2019 , the restore process will failed ? Or still pass , however whenever calling the CLR in new SQL Server will failed ?[/INST]The RESTORE will succeed. But if you have a safe assembly in the database, execution of modules defined from this assembly, will fail if the instance has "clr strict seurity" is set to 1, unless you apply any of the measures to make it trusted. Beware that CLR strict security can be enabled also on SQL 2012, SQL 2014 and SQL 2016 as detailed in [KB article 4018930].</s>
<s>[INST]How to select the optimal setting for SQL Server Network Packet Size Hi All, I recently ran into some connection problems with a SQL Server 2017 instance and the problem turned out to be Network Packet Size. The Packet Size setting was initially set to 16384. By dropping it down to 8192, the problem was solved. The error we were getting was 08501. Although the problem has been resolved, this made me wonder: 1. How do we determine the optimal setting of SQL Server Network Packet Size? 2. How does the initial installation of SQL Server choose the default setting? 3. What are the advantages/disadvantages of choosing a fixed TCP/IP port vs Dynamic Ports? 4. Why might I want to change the default port value of 1433? Thanks for your help! --Dan [/INST]The default value for this setting is 4096. If you had it at 16384, someone have been playing around. I recall that in some case I changed the network packet size, and I gained performance that way. But this was very long ago, probably SQL 6.5 or even older. And maybe the code I had written could better have been improved any other way. Anyway, if you want to find what is the optimal value for you, you will need to run your benchmarks. I would not be surprised if you find that 4096 or 8192 makes very little difference. Or just reset the value to 4096 and be done with it. > What are the advantages/disadvantages of choosing a fixed TCP/IP port vs Dynamic Ports? Some people disable the Broswer service to reduce the service area. In this case, you may prefer fixed ports, so that they don't move. You could also have users that connect is some funny way, so that they cannot use the Browser service. (Some my colleagues says this apply to them.) > Why might I want to change the default port value of 1433? Some people say that you should do this as a security measure to stop evil hackers from trying to sneak into your server. But this is only security by obscurity, and a very thin layer of obscurity. Scanning 65000 ports to see if there an SQL Server instance on them does not take that much time.</s>
<s>[INST]Failing Over on one of the SQL Server AG at one Location breaks the Distributed AG I have configured a SQL Server Distributed Availability Group (AG), containing a Windows cluster with an AG at one location, and a second cluster with its own AG at another location (thus, two AGs). Everything is working fine. However, upon failing over at the first location from the Primary Replica to the Secondary one in the first cluster/AG (not the Distributed AG), breaks the Distributed AG, and the node (of the Distributed AG) at the other location on the second AG shows as disconnected. Do I need to perform an additional step in order to complete the process? Thank you. J [/INST]A failover within a AG at one Location will cause the distributed availability group to re-establish the connection from the global primary. You may need to check the SQL Server Errorlog or Windows logs to see if there is relevant information that can help diagnose the problem.</s>
<s>[INST]Notification email when query results greater than 0 I'm looking for a way to get a email notification when query results are greater than 0 in a particular table. Is there a way to do this in SQL with a SQL Job or some other route? Your help is much appreciated!! Mike Hartman[/INST]Sure! Create an Agent job with a T-SQL jobstep where you do somethin along the lines of: IF EXISTS(SELECT * FROM ...) --Your query in parenthesis EXEC sp_send_dbmail ... Above assumes that you mean more than zero rows. If you mean sum aggregate function aggregating a value to something greater than zero, then adjust accordingly.</s>
<s>[INST]SQL Agent scheduled backup job run overlaps next scheduled backup job run? Hello, I have a nightly 8pm scheduled SQL 2014 Agent job MaintenancePlan backup job that does Full backups all of our DBs. One of our DBs is very large and is still running backup currently (confirms it is progressing but very slowly) from last night and looks like won't finish for about another day. Is it correct to say that since it looks like my nightly 8pm scheduled backup job will overlap tonight's scheduled 8pm run...it will not re-run since it's already running until current backup job finishes ? Thanks in advance.[/INST]SQL Agent jobs cannot start when already running. It will continue until it is done, and then set the next start date/time according to the schedule.</s>
<s>[INST]OLE DB provider "Microsoft.ACE.OLEDB.12.0" "Unspecified error". We are facing the following error while reading the excel file on our SQL instances using following query: Declare @filePath varchar(max)='E:\New folder\ZCWTest.xlsx' declare @qry varchar(max) set @qry = 'Select col1,col2 FROM OPENROWSET(''Microsoft.ACE.OLEDB.12.0'', ''Excel 12.0; Database=' + @filePath + ''',''select * from [sheet1$] '')' exec (@qry) and we are getting following error while executing the query: OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "Unspecified error". Msg 7303, Level 16, State 1, Line 1 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)". " Please let us know what is the solution for this error.[/INST]Please check below. 1. Which account that SQL server service is running under? Suggest you using local system account, a admin account or an account that has the read and write permissions on this excel file. 2. Please check that whether you have DisallowAdHocAccess registry key under. HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL14.MSSQLSERVER\Providers\Microsoft.ACE.OLEDB.12.0 We then executed below command and key got created automatically. USE [master] EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DisallowAdHocAccess', 0</s>
<s>[INST]The multi-part identifier could not be bound error. Hi everyone - Could you please help with this query. I know the error but is there any alternativefor this? Select * FROM #TempAutoclosure TmpAc INNER JOIN ( SELECT pa.applicationid ,pa.PaymentRequestID ,pa.CreateDateTime RequestedDate ,pa.FEInvoiceNumber ,TPr.PaymentRequestStatus FROM hydradb.dbo.PaymentRequest pa INNER JOIN ( SELECT DISTINCT prh.PaymentRequestID ,PRS.title PaymentRequestStatus FROM HYDRADB.dbo.PaymentRequestStatusHistory PRH INNER JOIN #TempPaymentHistory t ON t.PaymentRequestID = prH.PaymentRequestID AND t.Max_Createdatetime = PRH.Createdatetime LEFT JOIN HYDRADB.dbo.PaymentRequestStatus prs ON prs.PaymentRequestStatusId = prh.PaymentRequestStatusId WHERE prs.code IN ( 'Pending' ,'invalid' ,'Approved' ) AND datediff(dd, t.Max_Createdatetime, Getdate()) <= TmpAc.AssistanceInactivityAutoCloseDays --Check for Above filtered paymnets in last 120 days. ) TPr ON pa.PaymentRequestID = Tpr.PaymentRequestID ) pe ON pe.applicationid = TmpAc.applicationid[/INST]The following is an (educated?) guess. You have at least two problems. First, you cannot reference the TmpAc table inside a derived table that is INNER JOINed to the TmpAc table. Try changing that Inner Join to a CROSS APPLY and then change the final ON to a WHERE. Second, your WHERE prs.code IN ... effectively turns your LEFT JOIN into an INNER JOIN. You want that condition as part of the ON clause, not in the WHERE clause. So you can try Select * FROM #TempAutoclosure TmpAc CROSS APPLY ( SELECT pa.applicationid ,pa.PaymentRequestID ,pa.CreateDateTime RequestedDate ,pa.FEInvoiceNumber ,TPr.PaymentRequestStatus FROM hydradb.dbo.PaymentRequest pa INNER JOIN ( SELECT DISTINCT prh.PaymentRequestID ,PRS.title PaymentRequestStatus FROM HYDRADB.dbo.PaymentRequestStatusHistory PRH INNER JOIN #TempPaymentHistory t ON t.PaymentRequestID = prH.PaymentRequestID AND t.Max_Createdatetime = PRH.Createdatetime LEFT JOIN HYDRADB.dbo.PaymentRequestStatus prs ON prs.PaymentRequestStatusId = prh.PaymentRequestStatusId AND prs.code IN ( 'Pending' ,'invalid' ,'Approved' ) WHERE datediff(dd, t.Max_Createdatetime, Getdate()) <= TmpAc.AssistanceInactivityAutoCloseDays --Check for Above filtered paymnets in last 120 days. ) TPr ON pa.PaymentRequestID = Tpr.PaymentRequestID ) pe WHERE pe.applicationid = TmpAc.applicationid If that doesn't work, I would recommend you give us sample tables and data (in the form of CREATE TABLE and INSERT statements), a description of what you are trying to achieve, the results you want from the sample data you provided, and the release level of SQL Server you are using. That helps us understand exactly what you want and we can give a tested response.</s>
<s>[INST]Differences between the available languages of JDBC Drivers The SQL Server JDBC Driver is available for download on the Microsoft website in different languages - for example: - sqljdbc_9.4.0.0_enu.zip - sqljdbc_9.4.0.0_deu.zip - sqljdbc_9.4.0.0_fra.zip - (...) Can anyone tell me exactly how they differ? For example, is it only the language in which an error message is returned or are there more significant differences? Does the language selection of the driver influence the default language used to connect to the SQL Server? Kind Regards Oliver.[/INST]is it only the language in which an error message is returned AFAIK, yes, just localization of messages > Does the language selection of the driver influence the default language used to connect to the SQL Server? No, that language is controlled by the default language of the SQL Server login.</s>
<s>[INST]How to use where clause to get more than one value in sql server? Hi Team I am getting a one specific value when im using where clause. Is there a better to get other values when IN statement inside parameters is used? Please have a look at my query below > select > [Station Description] > [Transaction Code], > [DateTime Passed] > from [Tracking_Server_DB].[dbo].TS_Station as stn > inner join [Tracking_Server_DB].[dbo].[Checkpoint Movement] as mv > on stn.[Transaction Code] = mv.[Transaction Code] > where stn.[Station Description] IN ('T0011', 'M250', 'T0011') > and [DateTime Passed] = '2021-08-26 22:49:19.000' > order by [DateTime Passed] desc [/INST], The WHERE clause will return all rows that meet the conditions. The parameter IN will also return all rows that meet the condition. In other words, all rows that meet the conditions behind them will be returned. As pituach said, it may be that your JOIN statement filters out other rows. Please try the following code first to see if the JOIN sentence is incorrectly filtered: select [Station Description] [Transaction Code], [DateTime Passed] from [Tracking_Server_DB].[dbo].TS_Station as stn inner join [Tracking_Server_DB].[dbo].[Checkpoint Movement] as mv on stn.[Transaction Code] = mv.[Transaction Code] --where stn.[Station Description] IN ('T0011', 'M250', 'T0011') --and [DateTime Passed] = '2021-08-26 22:49:19.000' order by [DateTime Passed] desc If you have any question, please feel free to let me know.</s>
<s>[INST]How to use Add function in sql server? Hi Team I need some help, i don't have a record the filter the total of Station Description. What i want to achieve, if there is a way in sql server query. Where i can use Add function that will give me. Number of total Station Description per Date Time Passed column. Similar to Excel when we use SUM(..........). But the result when this is used i must get Transaction Code(Station Description) per total each and DateTime Passed be shown on my results. Let me share my logic its working but i want to implement if possible to this query. > select > [Station Description] > [Transaction Code], > [DateTime Passed] > from [Tracking_Server_DB].[dbo].TS_Station as stn > inner join [Tracking_Server_DB].[dbo].[Checkpoint Movement] as mv > on stn.[Transaction Code] = mv.[Transaction Code] > order by [DateTime Passed] desc [/INST]Gcobani \(EXTERN: VW S\.Africa\) , As mentioned by Erland, since you have [Transaction Code] columns in both tables, you have to identity which table it comes from. Please refer below updated ones. select count([Station Description]) total, stn.[Transaction Code], [DateTime Passed] from [Tracking_Server_DB].[dbo].TS_Station as stn inner join [Tracking_Server_DB].[dbo].[Checkpoint Movement] as mv on stn.[Transaction Code] = mv.[Transaction Code] group by stn.[Transaction Code],[DateTime Passed] order by [DateTime Passed] desc OR select distinct count([Station Description]) over (partition by [DateTime Passed]) total, stn.[Transaction Code], [DateTime Passed] from [Tracking_Server_DB].[dbo].TS_Station as stn inner join [Tracking_Server_DB].[dbo].[Checkpoint Movement] as mv on stn.[Transaction Code] = mv.[Transaction Code] order by [DateTime Passed] desc If above is still not working, please provide your CREATE TABLE statements for your tables together with INSERT statements with sample data, and the expected result of the sample. Then we could proceed to help you to enhance this query.</s>
<s>[INST]How to check for number of parentheses in a String - SQL I have an input string in the following format: DECLARE @input VARCHAR(2000) SET @input = '11.98, 123.007(p), 11.999, 12.998(p)(q),11.98(p)(q)(r)' While looping through each item in the list, I need to check the string for the number of parentheses it contains: one () or two () or three (). If there was one (), I was able to differentiate '11.98', '123.007(p)' using CharIndex('(', @EACHINPUTITEMFROMLIST) How do i check if the string has two or three parentheses? Please assist.[/INST]If your SQL server version is 2016 or later, try this: DECLARE @s varchar(20) = '11.98(p)(q)(r)'; SELECT COUNT(*) - 1 FROM STRING_SPLIT(@s, '(')</s>
<s>[INST]Problem reading xml nodes to a table Hi, I'm having issue reading all the ModelID's with respect to the Model. How do I get all ModelID's into the table w.r.t the CompanyCode DECLARE @XmlData XML SET @XmlData = '<Product> <Model CompanyCode="3020"> <ModelID>843743</ModelID> <ModelID>253463</ModelID> </Model> <Model CompanyCode="3021"> <ModelID>343253</ModelID> <ModelID>254262</ModelID> <ModelID>007007</ModelID> </Model> </Product>' DECLARE @Temp Table(tModel VARCHAR(50), ModelID Varchar(255)) INSERT INTO @Temp SELECT T.v.value('./@CompanyCode[1]', 'NVARCHAR(10)') AS CompanyCode, T.v.value('./ModelID[1]', 'NVARCHAR(10)') AS ModelID FROM @XmlData.nodes('/Product/Model') AS T(v) Select * FROM @Temp [/INST]Here is how to do it. **SQL** DECLARE @XmlData XML = N'<Product> <Model CompanyCode="3020"> <ModelID>843743</ModelID> <ModelID>253463</ModelID> </Model> <Model CompanyCode="3021"> <ModelID>343253</ModelID> <ModelID>254262</ModelID> <ModelID>007007</ModelID> </Model> </Product>'; SELECT p.value('@CompanyCode', 'NVARCHAR(10)') AS CompanyCode , c.value('(./text())[1]', 'NVARCHAR(10)') AS ModelID FROM @XmlData.nodes('/Product/Model') AS t1(p) CROSS APPLY t1.p.nodes('ModelID') AS t2(c); **Output** | CompanyCode | ModelID | | 3020 | 843743 | | 3020 | 253463 | | 3021 | 343253 | | 3021 | 254262 | | 3021 | 007007 |</s>
<s>[INST]Transactional replication, extra argument Procedure or function sp_MSupd_dboTableA has too many arguments specified. (Source: MSSQLServer, Error number: 8144) Using EXEC distribution.dbo.sp_browsereplcmds, I was able to pull the commands. --cmd 2 {CALL [sp_MSupd_dboTableA] (,,,,,,,,2021-08-30 22:13:03.847,,,,,,,,,,,,,,,,,,,,21099205,21125187,0x00010010)} --cmd 3 {CALL [sp_MSupd_dboTableA] (,,,,,,,,,2021-08-30 22:13:03.997,,,,,,,,,,,,,,,,,,,,21125187,0x00020000)} --cmd 4 {CALL [sp_MSupd_dboTableA] (,,,,,,,,2021-08-30 22:13:03.997,,,,,,,,,,,,,,,,,,,,,21125187,0x00010000)} How do I resolve this issue? What is the reason behind the extra arg, where could it be coming from?[/INST]Did you have Subscriber that is getting data from two (or more) different sources (Publishers)? If TableA on Subscriber getting data from Publisher1 and Publisher2. By default replication procedure names will have the same name “sp_Msupd_dboTableA” , that means both publishers will be using exact same procedure for insert, updates and deletes. You are receiving request from DEV to modify that table. To be exact drop a column. If you deploy change to Publisher1 only the replication procedure will be changed and new version (without dropped column) of the procedure will be applied on subscriber. The new procedure won’t have that old column… but what about Publisher2? Publisher2 will be trying to execute procedure still with old column and you will receive “Procedure or function sp_MSins_dboTableA has too many arguments specified.”.</s>