Hi :-PI have this SP[code]ALTER PROCEDURE GetDelayIntervalData(@start datetime, @stop datetime, @step int)ASDECLARE @steps bigintSET @steps = DATEDIFF(hour, @start, @stop)/ @stepDECLARE @i bigintSET @i=0DECLARE @tempStep varcharSET @tempStep = DATEPART(hour, @start)WHILE @i<@steps BEGIN SELECT (@tempStep) SET @tempStep = @tempStep + @step; SET @i = @i+1END[/code]Callin the SP [code]DECLARE @start datetime = convert(datetime, '2013-05-24 00:00:00', 120);DECLARE @stop datetime = convert(datetime, '2014-05-24 23:59:59', 120);execute dbo.GetDelayIntervalData @start, @stop, 1;[/code]Return "like a" bunch of tables (1X1)... how to output like a single result, concatenated table of [b]SELECT (@tempStep)[/b]?!Thanks Luka
↧
Stored procedure - how to return a single table
↧
query to return top 10 tables on each db on server
i need a query to return the top 10 tables in each database on a server. have used EXEC sp_msforeachtable 'sp_spaceused ''?''' which returns what I need for one db but I need it to loop through and gather the info for all dbs on server. maybe need cursor not sure. for reporting reasons i would like to include the name of the server and name of database. ThanksGeorge
↧
↧
Read all values from an xml node
Hi All,I have the following code and trouble reading values of Bank Accounts. If i remove the line it says "xmlns="http://applications.apch1.com/webservice/schema/" then i my query is working. But i cant remove this becasue that is what i will get response from a web service. All the records are stored in the database with this line included. Please help. Also please specify if there is any easy way to read these values.[code="sql"]DECLARE @MyXML XML SET @MyXML = '<GetEmployeeDetails xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <return xmlns="http://applications.apch1.com/webservice/schema/"> <CustomerID> A8339 </CustomerID> <BankAccounts> <BankAccount>123456</BankAccount> <BankAccount>7890123</BankAccount> </BankAccounts> </return></GetEmployeeDetails>' SELECT pref.value('./text()[1]', 'varchar(MAX)') AS 'BankAccount'FROM @MyXML.nodes('//GetEmployeeDetails/return/BankAccounts/child::node()') AS RequestXml(pref)where pref.value('local-name(.)[1]', 'varchar(100)') ='BankAccount'[/code]Thanks,Kum
↧
SQL works fine, but doe's not work called by a Stored Procedure
Hi, I have this code working fine:[code]DECLARE @startdate datetime = convert(datetime, '2013-05-24 20:00:00', 120);DECLARE @step bigint = 1;DECLARE @nextStartdate datetime = DATEADD(ss,@step*3600,@startdate);SELECT a.c1+ b.c2 + c.c3 + d.c4FROM (SELECT COALESCE(DATEDIFF(second, start_delay, end_delay),0) as c1 FROM DLY_DELAY WHERE start_delay >= @startdate AND end_delay <= @nextStartdate) a,(SELECT COALESCE(DATEDIFF(second, start_delay, @nextStartdate ),0) as c2 FROM DLY_DELAY WHERE start_delay >= @startdate AND start_delay < @nextStartdate AND end_delay > @nextStartdate) b,( SELECT COALESCE(DATEDIFF(second, @startdate, end_delay ),0) as c3 FROM DLY_DELAY WHERE start_delay < @startdate AND end_delay <= @nextStartdate AND end_delay > @startdate) c,( SELECT COALESCE((@step *3600),0) as c4 FROM DLY_DELAY WHERE start_delay < @startdate AND end_delay > @nextStartdate ) d[/code]Returning exactly what I need :) An [b]integer number[/b], representing the duration...but... integrating the same code in a Stored Procedure like this:[code]ALTER PROCEDURE GetDelayIntervalDuration(@startdate datetime, @step bigint)ASBEGINDECLARE @TempTable TABLE (result bigint)DECLARE @nextStartdate datetime = DATEADD(ss,@step*3600,@startdate);INSERT INTO @TempTable(result)SELECT a.c1+ b.c2 + c.c3 + d.c4FROM (SELECT COALESCE(DATEDIFF(second, start_delay, end_delay),0) as c1 FROM DLY_DELAY WHERE start_delay >= @startdate AND end_delay <= @nextStartdate) a,(SELECT COALESCE(DATEDIFF(second, start_delay, @nextStartdate ),0) as c2 FROM DLY_DELAY WHERE start_delay >= @startdate AND start_delay < @nextStartdate AND end_delay > @nextStartdate) b,( SELECT COALESCE(DATEDIFF(second, @startdate, end_delay ),0) as c3 FROM DLY_DELAY WHERE start_delay < @startdate AND end_delay <= @nextStartdate AND end_delay > @startdate) c,( SELECT COALESCE((@step *3600),0) as c4 FROM DLY_DELAY WHERE start_delay < @startdate AND end_delay > @nextStartdate ) d -- outputSELECT result FROM @TempTableEND;[/code]with the same input parameters returns an empty table/null/no results.[code]DECLARE @startdate datetime = convert(datetime, '2013-05-24 00:00:00', 120);DECLARE @step bigint = 1;execute dbo.GetDelayIntervalDuration @startdate, @step;[/code]What I'm I missing? :cool:SQL for my table[code]CREATE TABLE [dbo].[DLY_DELAY] ([DELAY_CNT] [dbo].[LongInt] NOT NULL,[START_DELAY] [dbo].[DTimeNull] NULL,[END_DELAY] [dbo].[DTimeNull] NULL)[/code]SQL - some data:[code]insert into [dbo].[DLY_DELAY]([DELAY_CNT],[START_DELAY],[END_DELAY]) values (36,'2013-05-24 20:47:00','2013-05-24 20:50:00')insert into [dbo].[DLY_DELAY]([DELAY_CNT],[START_DELAY],[END_DELAY]) values (37,'2013-05-24 20:57:00','2013-05-24 21:03:00')insert into [dbo].[DLY_DELAY]([DELAY_CNT],[START_DELAY],[END_DELAY]) values (38,'2013-05-24 19:57:00','2013-05-24 20:02:00')insert into [dbo].[DLY_DELAY]([DELAY_CNT],[START_DELAY],[END_DELAY]) values (39,'2013-05-24 19:57:00','2013-05-24 21:03:00')GO[/code]Thanks Luka :w00t:
↧
Return query with concatenating values.
I have two tables i am working with, they are "Institutions" and "InstitutionOversights". The relationship is one-to-many.The sample data is below.Table one:InstitutionID, InstName------------------------1 School Alpha2 School Beta3 School Charlie4 School DeltaTable two:InstitutionOversightID, InstitutionID, Type------------------------------------------------1 1 Accreditation2 1 Verifcation3 1 Old SystemI would like a query to return the results in the following format:InstitutionID, InstName, TypeList-----------------------------------------------1 School Alpha Accreditation, Verification, Old System2 School Beta null3 School Charlie null 4 School Delta null
↧
↧
convert nvarchar() to xml
HelloI use SET @text= CAST (@text AS xml) to convert @text to xml, but it didn't work and I have " % " instead of " < "Could you help me?
↧
Merge - Pros and cons
Hi there,Please any one help me out to understand what is MERGE ? and when to use it?Also explain me the Pros and cons.Thanks in Advance
↧
Could this be done better?
Howdy,Late last night I got a request for some data. The format was the biggest challenge, since the definitions of small, medium, and large businesses are different ranges for reach country, and the coded variables for them also end up being a different three number sequence for each country and business size. The format was:[quote]country, total, total small, total medium, total large[/quote]So I wrote this, altered a bit to accommodate the test data. I'm fine with how and how fast it works, so you don't have to rack your brain. But if you see an obvious improvement I'd love to hear it. [code="sql"]with data (orc_country, orc_quotacell, statusflag) as (select 'Canada', 1, 1 UNION ALL select 'Canada', 2, 1 UNION ALL select 'Canada', 3, 1 UNION ALL select 'Canada', 1, 1 UNION ALL select 'Canada', 2, 1 UNION ALL select 'Canada', 3, 1 UNION ALL select 'Canada', 2, 1 UNION ALL select 'Canada', 3, 1 UNION ALL select 'Canada', 3, 1 UNION ALL select 'Canada', 1, 1 UNION ALL select 'Canada', 2, 1 UNION ALL select 'India', 4, 1 UNION ALL select 'India', 5, 1 UNION ALL select 'India', 6, 1 UNION ALL select 'India', 4, 1 UNION ALL select 'India', 5, 1 UNION ALL select 'India', 6, 1 UNION ALL select 'India', 5, 1 UNION ALL select 'India', 6, 1 UNION ALL select 'India', 4, 1 UNION ALL select 'India', 5, 1 UNION ALL select 'India', 6, 1 UNION ALL select 'India', 5, 1 UNION ALL select 'India', 6, 1 UNION ALL select 'Singapore', 7, 1 UNION ALL select 'Singapore', 8, 1 UNION ALL select 'Singapore', 9, 1 UNION ALLselect 'Singapore', 7, 1 UNION ALL select 'Singapore', 8, 1 UNION ALL select 'Singapore', 9, 1 UNION ALL select 'Singapore', 7, 1 UNION ALL select 'Singapore', 8, 1 UNION ALL select 'Singapore', 9, 1 UNION ALL select 'Singapore', 8, 1 UNION ALL select 'Singapore', 9, 1 UNION ALLselect 'Thailand', 10, 1 UNION ALL select 'Thailand', 11, 1 UNION ALL select 'Thailand', 12, 1 UNION ALLselect 'Thailand', 10, 1 UNION ALL select 'Thailand', 11, 1 UNION ALL select 'Thailand', 12, 1 UNION ALLselect 'Thailand', 10, 1 UNION ALL select 'Thailand', 11, 1 UNION ALL select 'Thailand', 12, 1 UNION ALLselect 'Thailand', 11, 1 UNION ALL select 'Thailand', 12, 1 UNION ALL select 'UK', 13, 1 UNION ALL select 'UK', 14, 1 UNION ALL select 'UK', 15, 1 UNION ALL select 'UK', 13, 1 UNION ALL select 'UK', 13, 1 UNION ALL select 'UK', 14, 1 UNION ALL select 'UK', 15, 1 UNION ALL select 'UK', 14, 1 UNION ALL select 'UK', 14, 1 UNION ALL select 'UK', 15, 1 UNION ALL select 'UK', 14, 1 UNION ALL select 'UK', 15, 1 UNION ALL select 'United Arab Emirates', 16, 1 UNION ALL select 'United Arab Emirates', 17, 1 UNION ALL select 'United Arab Emirates', 16, 1 UNION ALL select 'United Arab Emirates', 16, 1 UNION ALL select 'United Arab Emirates', 17, 1 UNION ALL select 'United Arab Emirates', 16, 1 UNION ALL select 'United Arab Emirates', 17, 1 UNION ALLselect 'United Arab Emirates', 16, 1 UNION ALL select 'United Arab Emirates', 17, 1 UNION ALLselect 'United Arab Emirates', 16, 1 UNION ALL select 'United Arab Emirates', 17, 1 UNION ALLselect 'United Arab Emirates', 18, 1 ), agg(country, sm, md, lg) as (select s1.orc_country , min(s2.orc_quotacell) as [Sm] , min(s2.orc_quotacell) + 1 as [Med] , max(s2.orc_quotacell) as [Large]from data s1 left join data s2on s1.orc_country = s2.orc_countrygroup by s1.orc_country)select s.orc_country ,sum(case when s.orc_country = a.country then 1 else 0 end) as [Total] ,sum(case when s.orc_quotacell = a.sm then 1 else 0 end) as [Small] ,sum(case when s.orc_quotacell = a.md then 1 else 0 end) as [Medium] ,sum(case when s.orc_quotacell = a.lg then 1 else 0 end) as [Large]from data s, agg awhere s.statusflag = 1group by s.orc_countryorder by orc_country[/code]
↧
Need query - for table info
Hi There,I need query that results followings,Table name , Row Count, Size of TableThanks Many
↧
↧
MySQL To SQL Server
Guys,Actually I am doing a migration from MySQL to SQL Server. At the moment the database MySQL have a 80GB. I done all scripts to migrate.Informations:1. Windows Server 2008 R2 Enterprise Edition 64bits (8 Processors, 18GB Memory)2. SQL Server 2008 R2 Enterprise Edition 64bits (15GB Max Memory)3. I am using openrowset...4. All processor to be enabled...5. Simple (Recovery Model)6. Disks distinct (D: data, L: Log, T: TempDB) I want know if exist best practices(parameters, tips or anymore) to SQL Server to import big data volume...
↧
RANGE OF DATES
GoodnightWould like to separate the dates for months. For example I have a table that shows me the following:Code Name fec_fin justification fec_ini 1 john 15/03/2013 Holiday 13/04/2013What I want is that the range is separated for their respective months for example:Code Name fec_fin justification fec_ini1 john 15/03/2013 Holiday 31/03/20131 john 01/04/2013 Holiday 13/04/2013As you can see that time has been separated into two sections, for months.Keep in mind that the table exists and records that have been separated for months but many more to go missing are like 18000 records.thanks
↧
fragmentation question
i have a quick question about internal fragmentationthe book explanation is that DML statement cause internal fragmentation, i can understand how UPDATE and DELETE leads to fragmentation but i don't understand how INSERT doescan anyone please explain this to me
↧
Dynamic Pivot with subgrouping
Hi All,Wondered if someone could possibly help me with a pivot question.I am trying to pivot some data as you would normally however I am trying to also group the pivot into three sub column groups too.Basically the scenario is that I have three sub groups Budget, Person, RenewalDate for each Service (Service being the pivot point). So for each unique service I want to display the budget person and renewal date for each service by company.I have created two tables to illustrate the base data and the required output. Would someone please be kind enough to explain perhaps with an example of how I can do this? It would be also great if I could be shown how to do this dynamically too because the number of Services is unknown, i.e. it could be 4 Services or 20, each with three sub columns, budget, person and renewal date.Please find code below. It should be quite self explanatory as to what I am trying to do. But please let me know if you need any more information.Many thanks in advance.IMPORTANT:1. I really need it to be dynamic2. the Services are not standardised names, they are numbered for illustration purposes only, they vary in naming convention.[code="sql"]create table #BaseData ( Company nvarchar(100), Person nvarchar(50), [Service] nvarchar(100), Budget int, RenewalDate datetime)insert into #BaseData(Company, Person, [Service], Budget, RenewalDate)select 'A', 'Siwel Noswod', 'Service1', 40, '2014-07-01 00:00:00.000'insert into #BaseData(Company, Person, [Service], Budget, RenewalDate)select 'A', 'Siwel Noswod', 'Service2', 60, '2013-11-01 00:00:00.000'insert into #BaseData(Company, Person, [Service], Budget, RenewalDate)select 'B', 'Joe Bloges', 'Service1', 50, '2014-06-01 00:00:00.000'insert into #BaseData(Company, Person, [Service], Budget, RenewalDate)select 'B', 'Siwel Noswod', 'Service2', 20, '2014-10-01 00:00:00.000'insert into #BaseData(Company, Person, [Service], Budget, RenewalDate)select 'C', 'Joe Bloges', 'Service1', 68, '2012-01-01 00:00:00.000'insert into #BaseData(Company, Person, [Service], Budget, RenewalDate)select 'C', 'Micheal', 'Service3', 11, '2012-09-01 00:00:00.000'insert into #BaseData(Company, Person, [Service], Budget, RenewalDate)select 'D', 'Joe Bloges', 'Service3', 88, '2010-03-01 00:00:00.000'select * from #BaseDatadrop table #BaseDatacreate table #RequiredOutput( Company nvarchar(100), Service1Budget int, Service1Person nvarchar(100), Service1RenewalDate datetime, Service2Budget int, Service2Person nvarchar(100), Service2RenewalDate datetime, Service3Budget int, Service3Person nvarchar(100), Service3RenewalDate datetime )insert into #RequiredOutput(Company, Service1Budget, Service1Person, Service1RenewalDate, Service2Budget, Service2Person, Service2RenewalDate)select 'A', 40, 'Siwel Noswod', '2014-07-01 00:00:00.000', 60, 'Siwel Noswod', '2013-11-01 00:00:00.000'insert into #RequiredOutput(Company, Service1Budget, Service1Person, Service1RenewalDate, Service2Budget, Service2Person, Service2RenewalDate)select 'B', 50, 'Joe Bloges', '2014-06-01 00:00:00.000', 20, 'Siwel Noswod', '2014-10-01 00:00:00.000'insert into #RequiredOutput(Company, Service1Budget, Service1Person, Service1RenewalDate, Service3Budget, Service3Person, Service3RenewalDate)select 'C', 68, 'Joe Bloges', '2012-01-01 00:00:00.000', 11, 'Michael', '2012-09-01 00:00:00.000'insert into #RequiredOutput(Company, Service3Budget, Service3Person, Service3RenewalDate)select 'D', 88, 'Joe Bloges', '2010-03-01 00:00:00.000'select * from #RequiredOutputdrop table #RequiredOutput[/code]
↧
↧
Download resul set in .csv
Hello.Could you help me? please.I have a task, download resul set in .csv declare @cmd varchar(8000)set @cmd= 'bcp "[Devel].TestDB.dbo.ia_ReportUser" out "C:\TEMP1\2255212.csv" -c -t"," -T -S '+@@servernameexec master..xp_cmdshell @cmd ,no_outputBut when i start this scrip, i have a messageA valid table name is required for in, out, or format options.Please help me sove this task.Thank you very much.
↧
how to set some restriction on table names while creating?
Hi There,I need to ensure some naming standards to users while creating tables.All table name should be in same pattern (ie., ) TeamName_EmpId_tablenameI need a way to restrict user to follow the naming standard. If any user tries to create table without the above naming standard system should not allow.could any1 help me regards this?Thanks
↧
How can I solve Null value is eliminated by an aggregate or other SET operation?
HelloI execute the code below[code="plain"]declare @LastDate datetimeSELECT @LastDate = max([LastUpdate]) FROM [exhibitor].[dbo].[blgBelongs] WHERE (([Table1]=@module1 OR [Table2]=@module2 )or ([Table2]=@module1 OR [Table1]=@module2 ) AND Exists (SELECT [Table1],[Table1ID] FROM [exhibitor].[dbo].[blgBelongs] WHERE table2=30 and table2ID=@dmn_ID))[/code]Befor I see @LastDate , I see this warningWarning: Null value is eliminated by an aggregate or other SET operation.Could you help me how can I solve it?
↧
Handling of SP failure within the calling SP
Hello,I'm trying to find the most efficient way of handling failures in a process that looks like this:CREATE PROCEDURE SP_CALCASBEGIN ... some logic... ... get a set of values from a queue table ...-- exec several SP's for the values from the queue EXEC SP_1 EXEC SP_2 ... EXEC SP_N ... delete the processed values from the queueENDThe issue I noticed is that since there is no error handling in the calling procedure it is possible for one or more of the SP_N to fail but execution of SP_CALC will continue and the queue will still get deleted. Therefore the values may never get processed for this SP_N. The success of this process is critical to the functionality of the application it supports, it is resource intensive, runs a few times every minute, and there is error handling in each of the SP_N that causes them to rollback and return control to the caller. I've tried a few things with the usual TRY..CATCH. My goal is to delete the queue only if all SP_N have succeeded and to rerun only the failed SP(I experimented with @retry in a loop for a preset number of times). Not sure if that's the best way to do it and not sure how to handle cases when SP_N doesn't succeed after a couple of retries.If anyone has worked on a similar problem before, please share your experience.
↧
↧
Need Help Onthis Query?
hi to all,i am facing issue for the following query:for set @FromDate='1/1/2013' set @ToDate='1/14/2013' for this date the sum output is showing correct,but i have changed the todate asset @FromDate='1/1/2013' set @ToDate='1/30/2013' exact output not displayedplease help me on this:declare @FromDate datedeclare @ToDate datedeclare @Timeperiod varchar(30)='Weekly'declare @vendor varchar(50)='V00616' set @FromDate='1/1/2013' set @ToDate='1/30/2013'if(@Timeperiod='Weekly')begin;with cte as( SELECT CASE DATEPART(WEEKDAY,@FromDate) WHEN 1 THEN DATEadd (DAY,5,@FromDate) WHEN 2 THEN DATEadd (DAY,4,@FromDate) WHEN 3 THEN DATEadd (DAY,3,@FromDate) WHEN 4 THEN DATEadd (DAY,2,@FromDate) WHEN 5 THEN DATEadd (DAY,1,@FromDate) WHEN 6 THEN DATEadd (DAY,0,@FromDate) WHEN 7 THEN DATEadd (DAY,6,@FromDate)END WeekEnding,@ToDate EndDateunion allselect dateadd(Wk, 1, WeekEnding),dateadd(Wk, 1, EndDate)from ctewhere dateadd(Wk, 0, WeekEnding) < =@ToDate )select WeekEnding,((SELECT sum([Quantity]) from [table]where ([ Date] Between WeekEnding and EndDate ))+(select sum([Quantity]) from [table1]where ([Document Type]= 1) and ([Item Category Code] = 'STYLES') and([Buy-from Vendor No_] in (@vendor)) and ([Quantity]>0) and ([Prod_ Order No_]='') and ([ Date] Between WeekEnding and EndDate))) 'Items Ordered from QT (MPRO/PO)'from cte end
↧
Need a 2nd opinion on a query
I had a collegue write the following query. He got defensive when I asked what he was trying to accomplish with it. [code="sql"]Select count(*) from tblevent a inner join tblevent b on a.omsid = b.omsid And a.Recordtype = 'promo' and b.recordtype = 'event' [/code]The column recordtype can only be 'promo' or 'event'.Im thinking this is performing a join on one table joining with itself based on OMSID matching, then filtering out the records from table 'a' where recordtype was 'event' and filtering out table b where recordtype = 'promo'. either way I dont think he was getting anything of value.
↧
Concatenation & Dynamic-SQL (Unexpected Behavior)...
So, I have a query which uses dynamic-SQL. I noticed some unexpected behavior. I will try to simplify it. If, for example, I run the following (large) code:[code="sql"]DECLARE @SQL_String AS NVARCHAR (MAX)SET @SQL_String = N' --Filler to exceed 4000 characters. Filler to exceed 4000 characters. Filler to exceed 4000 characters. Filler to exceed 4000 characters. --Filler to exceed 4000 characters. Filler to exceed 4000 characters. Filler to exceed 4000 characters. Filler to exceed 4000 characters. --Filler to exceed 4000 characters. Filler to exceed 4000 characters. Filler to exceed 4000 characters. Filler to exceed 4000 characters. --Filler to exceed 4000 characters. Filler to exceed 4000 characters. Filler to exceed 4000 characters. Filler to exceed 4000 characters. SELECT sqIF.[type] AS object_type ,DB_NAME () AS database_name ,SCHEMA_NAME (sqIF.[schema_id]) AS [schema_name] ,sqIF.[object_name] ,sqIF.index_name ,sqIF.index_key ,sqIF.include_key ,REVERSE (SUBSTRING (REVERSE (CONVERT (VARCHAR (23), CONVERT (MONEY, sqIF.avg_fragmentation_in_percent), 1)), 1, 23)) AS fragmentation ,sqIF.type_desc AS index_type ,(CASE sqIF.is_primary_key WHEN 0 THEN ''No'' WHEN 1 THEN ''Yes'' ELSE ''N/A'' END) AS is_pk ,(CASE sqIF.is_unique WHEN 0 THEN ''No'' WHEN 1 THEN ''Yes'' ELSE ''N/A'' END) AS is_unique ,caREC.recommendation ,N''USE ['' + DB_NAME () + N'']; ALTER INDEX ['' + sqIF.index_name + N''] ON ['' + SCHEMA_NAME (sqIF.[schema_id]) + N''].['' + sqIF.[object_name] + N''] '' + caREC.recommendation + (CASE caREC.recommendation WHEN ''REBUILD'' THEN N'' WITH (MAXDOP = 1)'' ELSE N'''' END) + N'';'' AS alter_index_statement FROM ( SELECT O.[type] ,O.[schema_id] ,O.name AS [object_name] ,I.name AS index_name ,STUFF (CONVERT (NVARCHAR (MAX), (caIIF.index_key)), 1, 2, N'''') AS index_key ,ISNULL (STUFF (CONVERT (NVARCHAR (MAX), (caIIF.include_key)), 1, 2, N''''), N'''') AS include_key ,DDIPS.avg_fragmentation_in_percent ,I.type_desc ,I.is_primary_key ,I.is_unique ,ROW_NUMBER () OVER ( PARTITION BY I.name ORDER BY DDIPS.avg_fragmentation_in_percent DESC ) AS row_number_id FROM sys.dm_db_index_physical_stats (1, NULL, NULL, NULL, N''LIMITED'') DDIPS INNER JOIN sys.objects O ON O.[object_id] = DDIPS.[object_id] AND O.[type] IN (''U'', ''V'') AND O.is_ms_shipped = 0 AND NOT ( SCHEMA_NAME (O.[schema_id]) = N''dbo'' AND O.name = N''sysdiagrams'' AND O.[type] = ''U'' ) INNER JOIN sys.indexes I ON I.[object_id] = DDIPS.[object_id] AND I.index_id = DDIPS.index_id AND I.is_disabled <> 1 AND I.is_hypothetical <> 1 CROSS APPLY ( SELECT ( SELECT N'', '' + C.name AS [text()] FROM sys.index_columns IC INNER JOIN sys.columns C ON C.[object_id] = IC.[object_id] AND C.column_id = IC.column_id WHERE IC.is_included_column = 0 AND IC.[object_id] = I.[object_id] AND IC.index_id = I.index_id ORDER BY IC.key_ordinal FOR XML PATH ('''') ,TYPE ) AS index_key ,( SELECT N'', '' + C.name AS [text()] FROM sys.index_columns IC INNER JOIN sys.columns C ON C.[object_id] = IC.[object_id] AND C.column_id = IC.column_id WHERE IC.is_included_column = 1 AND IC.[object_id] = I.[object_id] AND IC.index_id = I.index_id ORDER BY IC.key_ordinal FOR XML PATH ('''') ,TYPE ) AS include_key ) caIIF WHERE DDIPS.index_id <> 0 AND DDIPS.avg_fragmentation_in_percent > 5 ) sqIF CROSS APPLY ( SELECT (CASE WHEN sqIF.avg_fragmentation_in_percent <= 30.0 THEN ''REORGANIZE'' ELSE ''REBUILD'' END) AS recommendation ) caREC WHERE sqIF.row_number_id = 1 'EXECUTE (@SQL_String)SELECT LEN (@SQL_String)[/code]Everything runs as expected. If I try to concatenate something to the code I get an error. For example, replace the following:[code="sql"] --Filler to exceed 4000 characters. Filler to exceed 4000 characters. Filler to exceed 4000 characters. Filler to exceed 4000 characters. SELECT sqIF.[type] AS object_type ,DB_NAME () AS database_name[/code]with:[code="sql"] --Filler to exceed 4000 characters. Filler to exceed 4000 characters. Filler to exceed 4000 characters. Filler to exceed 4000 characters.'+' SELECT sqIF.[type] AS object_type[/code]I've essentially concatenated nothing new / additional to the code, but it errors out. When I break it down, what is happening is the concatenation seems to be limiting / truncating to NVARCHAR (4000). What I don't understand is why. It seems that when it is all one string it can go to NVARCHAR (MAX), but if you concatenate it goes down to NVARCHAR (4000).Forgive my ignorance, just trying to understand why it works this way. Especially since if I update the changed code to:[code="sql"] --Filler to exceed 4000 characters. Filler to exceed 4000 characters. Filler to exceed 4000 characters. Filler to exceed 4000 characters.'+CONVERT (NVARCHAR (MAX), N'')+' SELECT sqIF.[type] AS object_type[/code]...everything works fine again.I am thinking it has something to do with implicit conversions, but I was expecting it to implicitly convert to NVARCHAR (MAX)... Not, seemingly, NVARCHAR (4000).Again, sorry for my ignorance and somewhat simplified (yet long) example.Thanks all.
↧