Search Results

Search found 1214 results on 49 pages for 'tomaz tsql'.

Page 11/49 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Saving a select count(*) value to an integer (SQL Server)

    - by larryq
    Hi everyone, I'm having some trouble with this statement, owing no doubt to my ignorance of what is returned from this select statement: declare @myInt as INT set @myInt = (select COUNT(*) from myTable as count) if(@myInt <> 0) begin print 'there's something in the table' end There are records in myTable, but when I run the code above the print statement is never run. Further checks show that myInt is in fact zero after the assignment above. I'm sure I'm missing something, but I assumed that a select count would return a scalar that I could use above?

    Read the article

  • T-SQL Right Joins to ALL Entries inc Selected Column

    - by Pace
    Hi Experts, I have the following Query which produces the output below; SELECT TBLUSERS.USERID, TBLUSERS.ADusername, TBLACCESSLEVELS.ACCESSLEVELID, TBLACCESSLEVELS.AccessLevelName FROM TBLACCESSLEVELS INNER JOIN TBLACCESSRIGHTS ON TBLACCESSLEVELS.ACCESSLEVELID = TBLACCESSRIGHTS.ACCESSLEVELID INNER JOIN TBLUSERS ON TBLACCESSRIGHTS.USERID = TBLUSERS.USERID The output is this; 29 administrator 1 AllUsers 29 administrator 2 JobQueue 29 administrator 3 Telephone Directory Admin 29 administrator 4 Jobqueueadmin 29 administrator 5 UserAdmin 29 administrator 6 Product System 27 alan 1 AllUsers 97 andy 1 AllUsers 26 barry 1 AllUsers 26 barry 2 JobQueue 26 barry 3 Telephone Directory Admin 26 barry 4 Jobqueueadmin 26 barry 5 UserAdmin 26 barry 6 Product System 26 barry 7 Newseditor 26 barry 8 GreetingBoard What I would like to do is modify the query so I get all Access Levels regardless of weather there is an entry for that user. What I would also like to do is some sort of exist case so that I get output like the following; 29 administrator 1 AllUsers True 29 administrator 2 JobQueue True 29 administrator 3 Telephone Directory Admin True 29 administrator 4 Jobqueueadmin True 29 administrator 5 UserAdmin True 29 administrator 6 Product System True 29 administrator 7 Newseditor False 29 administrator 8 GreetingBoard False 27 alan 1 AllUsers True 27 alan 2 JobQueue False 27 alan 3 Telephone Directory Admin False 27 alan 4 Jobqueueadmin False 27 alan 5 UserAdmin False 27 alan 6 Product System False 27 alan 7 Newseditor False 27 alan 8 GreetingBoard False 97 andy 1 AllUsers True 97 andy 2 JobQueue False 97 andy 3 Telephone Directory Admin False 97 andy 4 Jobqueueadmin False 97 andy 5 UserAdmin False 97 andy 6 Product System False 97 andy 7 Newseditor False 97 andy 8 GreetingBoard False 26 Barry 1 AllUsers True 26 Barry 2 JobQueue True 26 Barry 3 Telephone Directory Admin True 26 Barry 4 Jobqueueadmin True 26 Barry 5 UserAdmin True 26 Barry 6 Product System True 26 Barry 7 Newseditor True 26 Barry 8 GreetingBoard True ......................................... So the rules are ALWAYS show ALL Entries for ACCESSLEVELS and where EXISTS in ACCESSRIGHTS produce a true / false to show this. I hope this makes sense and hopefully you dont need the table definitions as everything I need to work with is in the original Query. I just need a way of manipulating it slightly and getting the join in the right place. Thank you. Pace

    Read the article

  • SQL Server PIVOT with multiple X-axis columns

    - by HeavenCore
    Take the following example data: Payroll Forname Surname Month Year Amount 0000001 James Bond 3 2011 144.00 0000001 James Bond 6 2012 672.00 0000001 James Bond 7 2012 240.00 0000001 James Bond 8 2012 1744.50 0000002 Elvis Presley 3 2011 1491.00 0000002 Elvis Presley 6 2012 189.00 0000002 Elvis Presley 7 2012 1816.50 0000002 Elvis Presley 8 2012 1383.00 How would i PIVOT this on the Year + Month (eg: 201210) but preserve Payroll, Forename & Surname as seperate columns, for example, the above would become: Payroll Forename Surname 201103 201206 201207 201208 0000001 James Bond 144.00 672.00 240.00 1744.50 0000002 Elvis Presley 1491.00 189.00 1816.50 1383.00 I'm assuming that because the Year + Month names can change then i will need to employ dynamic SQL + PIVOT - i had a go but couldnt even get the code to parse, nevermind run - any help would be most appreciated! Edit: What i have so far: INSERT INTO #tbl_RawDateBuffer ( PayrollNumber , Surname , Forename , [Month] , [Year] , AmountPayable ) SELECT PayrollNumber , Surname , Forename , [Month] , [Year] , AmountPayable FROM RawData WHERE [Max] > 1500 DECLARE @Columns AS NVARCHAR(MAX) DECLARE @StrSQL AS NVARCHAR(MAX) SET @Columns = STUFF((SELECT DISTINCT ',' + QUOTENAME(CONVERT(VARCHAR(4), c.[Year]) + RIGHT('00' + CONVERT(VARCHAR(2), c.[Month]), 2)) FROM #tbl_RawDateBuffer c FOR XML PATH('') , TYPE ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') SET @StrSQL = 'SELECT PayrollNumber, ' + @Columns + ' from ( select PayrollNumber , CONVERT(VARCHAR(4), [Year]) + RIGHT(''00'' + CONVERT(VARCHAR(2), [Month]), 2) dt from #tbl_RawDateBuffer ) x pivot ( sum(AmountPayable) for dt in (' + @Columns + ') ) p ' EXECUTE(@StrSQL) DROP TABLE #tbl_RawDateBuffer

    Read the article

  • SQL Server: SELECT rows with MAX(Column A), MAX(Column B), DISTINCT by related columns

    - by z531
    Scenario: Table A MasterID, Added Date, Added By, Updated Date, Updated By, 1, 1/1/2010, 'Fred', null, null 2, 1/2/2010, 'Barney', 'Mr. Slate', 1/7/2010 3, 1/3/2010, 'Noname', null, null Table B MasterID, Added Date, Added By, Updated Date, Updated By, 1, 1/3/2010, 'Wilma', 'The Great Kazoo', 1/5/2010 2, 1/4/2010, 'Betty', 'Dino', 1/4/2010 Table C MasterID, Added Date, Added By, Updated Date, Updated By, 1, 1/5/2010, 'Pebbles', null, null 2, 1/6/2010, 'BamBam', null, null Table D MasterID, Added Date, Added By, Updated Date, Updated By, 1, 1/2/2010, 'Noname', null, null 3, 1/4/2010, 'Wilma', null, null I need to return the max added date and corresponding user, and max updated date and corresponding user for each distinct record when tables A,B,C&D are UNION'ed, i.e.: 1, 1/5/2010, 'Pebbles', 'The Great Kazoo', 1/5/2010 2, 1/6/2010, 'BamBam', 'Mr. Slate', 1/7/2010 3, 1/4/2010, 'Wilma', null, null I know how to do this with one date/user per row, but with two is beyond me. DBMS is SQL Server 2005. T-SQL solution preferred. Thanks in advance, Dave

    Read the article

  • Dynamic SQL to generate column names?

    - by Ben McCormack
    I have a query where I'm trying pivot row values into column names and currently I'm using SUM(Case...) As 'ColumnName' statements, like so: SELECT SKU1, SUM(Case When Sku2=157 Then Quantity Else 0 End) As '157', SUM(Case When Sku2=158 Then Quantity Else 0 End) As '158', SUM(Case When Sku2=167 Then Quantity Else 0 End) As '167' FROM OrderDetailDeliveryReview Group By OrderShipToID, DeliveryDate, SKU1 The above query works great and gives me exactly what I need. However, I'm writing out the SUM(Case... statements by hand based on the results of the following query: Select Distinct Sku2 From OrderDetailDeliveryReview Is there a way, using T-SQL inside a stored procedure, that I can dynamically generate the SUM(Case... statements from the Select Distinct Sku2 From OrderDetailDeliveryReview query and then execute the resulting SQL code?

    Read the article

  • Sqldatareader and rowcount

    - by phenevo
    Hi, I have a query: declare @Code nvarchar(100) select @Code="BMW" select name from NewCars where code=@Code if @@rowcount = 0 Select name from OldCars where code=@Code In Sql managment studio first part give me 0 resuklts, and second 1 one result, and that is ok, but in sqldatareader I use the same query ofcource without: declare @Code nvarchar(100) select @Code="BMW" because I use: cmd.Parameters.AddWithValue("@Code", "BMW"); And using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.HasRows) { while (reader.Read()) { Name= reader["Name"].ToString(); } } else { throw new NotSupportedException("Lack of car with this Code"); } } gives me zero result

    Read the article

  • PRINT statement in T-SQL

    - by ProfK
    Why does the PRINT statement in T-SQL seem to only sometimes work? What are the constraints on using it? It seems sometimes if a result set is generated, it becomes a null function, I assumed to prevent corrupting the resultset, but could it's output not go out in another result set, such as the row count?

    Read the article

  • Pretty Printer for T-SQL?

    - by Paul
    I'm looking for a good T-SQL Pretty Printer so that all the code looks consistant between developers in our project. Preferably a free/open source one, but paid for isn't out of the realms of possibility as long as it's reasonably priced. Are there any particular industry leaders? I'm not that fussed about what particular standard it uses, but the more configurable the better. That way we can have little style wars among the developers and have a bit of fun to boot. ;-) I suppose I should add that Visual Studio and Management Studio integration would be considered favourably.

    Read the article

  • Getting XQuery [modify()]: Top-level attribute nodes are not supported error while modifying xml

    - by sam
    DECLARE @mycur CURSOR DECLARE @id int DECLARE @ParentNodeName varchar(max) DECLARE @NodeName varchar(max) DECLARE @NodeText varchar(max) SET @mycur = CURSOR FOR SELECT * FROM @temp OPEN @mycur FETCH NEXT FROM @mycur INTO @id,@ParentNodeName,@NodeName,@NodeText WHILE @@FETCH_STATUS = 0 BEGIN PRINT @id -- sample statements PRINT @ParentNodeName PRINT @NodeName SET @x.modify (' insert attribute status {sql:variable("@status")} as first into (/@ParentNodeName/@NodeName/child::*[position()=sql:variable("@status")])[1] ') FETCH NEXT FROM @mycur INTO @id,@ParentNodeName,@NodeName,@NodeText END DEALLOCATE @mycur Any idea why I am getting this error as query works fine if I manually insert path

    Read the article

  • Status of Data in Rollback of Large Transaction in SQL Server

    - by Lloyd Banks
    I have a data warehousing procedure that downloads and replaces dozens of tables from a linked server to a local database. Every once in a while, the code will get stuck on one of the tables on the linked server because the table on the linked server is in a state of transition. I am under the assumption that since the entire procedure is considered one transaction commit, when the procedure gets stuck, none of the changes made by the procudure so far would have committed. But the opposite seems to be true, tables that were "downloaded" before the procedure got stuck would have been updated with today's versions on the local server. Shouldn't SQL Server wait for the entire procedure to finish before the changes are durable? CREATE PROCEDURE MYIMPORT AS BEGIN SET NOCOUNT ON IF EXISTS (SELECT * FROM INFORMATION.SCHEMA.TABLES WHERE TABLE_NAME = 'TABLE1') DROP TABLE TABLE1 SELECT COLUMN1, COLUMN2, COLUMN3 INTO TABLE1 FROM OPENQUERY(MYLINK, 'SELECT COLUMN1, COLUMN2, COLUMN3 FROM TABLE1') IF EXISTS (SELECT * FROM INFORMATION.SCHEMA.TABLES WHERE TABLE_NAME = 'TABLE2') DROP TABLE TABLE2 SELECT COLUMN1, COLUMN2, COLUMN3 INTO TABLE2 FROM OPENQUERY(MYLINK, 'SELECT COLUMN1, COLUMN2, COLUMN3 FROM TABLE2') --IF THE PROCEDURE GETS STUCK HERE, THEN CHANGES TO TABLE1 WOULD HAVE BEEN MADE ON THE LOCAL SERVER WHILE NO CHANGES WOULD HAVE BEEN MADE TO TABLE3 ON THE LOCAL SERVER IF EXISTS (SELECT * FROM INFORMATION.SCHEMA.TABLES WHERE TABLE_NAME = 'TABLE3') DROP TABLE TABLE3 SELECT COLUMN1, COLUMN2, COLUMN3 INTO TABLE3 FROM OPENQUERY(MYLINK, 'SELECT COLUMN1, COLUMN2, COLUMN3 FROM TABLE3') END

    Read the article

  • T-SQL IsNumeric() and Linq-to-SQL

    - by cdonner
    I need to find the highest value from the database that satisfies a certain formatting convention. Specifically, I would like to fund the highest value that looks like EU999999 ('9' being any digit) select max(col) will return something like 'EUZ...' for instance that I want to exclude. The following query does the trick, but I can't produce this via Linq-to-SQL. There seems to be no translation for the isnumeric() function in SQL Server. select max(col) from table where col like 'EU%' and 1=isnumeric(replace(col, 'EU', '')) Writing a database function, stored procedure, or anything else of that nature is far down the list of my preferred solutions, because this table is central to my app and I cannot easily replace the table object with something else. What's the next-best solution?

    Read the article

  • Inserting Parameters, C#, T-Sql

    - by jpavlov
    I am trying to insert a parameter through an aspx page via text box. I set my parameters up, but evertime I executenonquery, the @Username shows up in the database instead of the actual value. Below is my code. Can anyone shed a little insight? SqlParameter @UserName = new SqlParameter("@UserName", System.Data.SqlDbType.VarChar); @UserName.Direction = ParameterDirection.Input; @UserName.Value = txtUserName.Text; cmd.Parameters.Add(@UserName);

    Read the article

  • Conditional Operator in SQL Where Clause

    - by Marc
    I'm wishing I could do something like the following in SQl Server 2005 (which I know isnt valid) for my where clause. Sometimes @teamID (passed into a stored procedure) will be the value of an existing teamID, otherwise it will always be zero and I want all rows from the Team table. I researched using Case and the operator needs to come before or after the entire statement which prevents me from having a different operator based on the value of @teamid. Any suggestions other than duplicating my select statements. declare @teamid int set @teamid = 0 Select Team.teamID From Team case @teamid when 0 then WHERE Team.teamID > 0 else WHERE Team.teamID = @teamid end

    Read the article

  • Aggregate survey results recursively by manager

    - by Ian Roke
    I have a StaffLookup table which looks like this. UserSrn | UserName | ManagerSrn =============================== ABC1 | Jerome | NULL ABC2 | Joe | ABC1 ABC3 | Paul | ABC2 ABC4 | Jack | ABC3 ABC5 | Daniel | ABC3 ABC6 | David | ABC2 ABC7 | Ian | ABC6 ABC8 | Helen | ABC6 The staff structure looks like this. |- Jerome | |- Joe || ||- Paul ||| |||- Jack ||| |||- Daniel || ||- David ||| |||- Ian ||| |||- Helen I have a list of SurveyResponses that looks like this. UserSrn | QuestionId | ResponseScore ==================================== ABC2 | 1 | 5 ABC2 | 3 | 4 ABC4 | 16 | 3 ... What I am trying to do sounds pretty simple but I am struggling to find a neat, quick way of doing it. I want to create a sproc that takes an Srn and returns back all the staff under that Srn in the structure. If there is a score for QuestionId of 16 then that indicates a completed survey. I would like to return a line for the Srn entered (The top manager) with a count of completed surveys for the direct reports under that manager. Under that I would like each manager under the original manager with a count of completed surveys for each of their direct reports and so on. I would like to see the data as such below when I set the top manager to be Joe (ABC2). UserName | Completed | Total ============================ Joe | 2 | 2 Paul | 1 | 2 David | 0 | 2 TOTAL | 3 | 6

    Read the article

  • LEFT OUTER JOIN in Linq - How to Force

    - by dodegaard
    I have a LEFT OUTER OUTER join in LINQ that is combining with the outer join condition and not providing the desired results. It is basically limiting my LEFT side result with this combination. Here is the LINQ and resulting SQL. What I'd like is for "AND ([t2].[EligEnd] = @p0" in the LINQ query to not bew part of the join condition but rather a subquery to filter results BEFORE the join. Thanks in advance (samples pulled from LINQPad) - Doug (from l in Users join mr in (from mri in vwMETRemotes where met.EligEnd == Convert.ToDateTime("2009-10-31") select mri) on l.Mahcpid equals mr.Mahcpid into lo from g in lo.DefaultIfEmpty() orderby l.LastName, l.FirstName where l.LastName.StartsWith("smith") && l.DeletedDate == null select g) Here is the resulting SQL -- Region Parameters DECLARE @p0 DateTime = '2009-10-31 00:00:00.000' DECLARE @p1 NVarChar(6) = 'smith%' -- EndRegion SELECT [t2].[test], [t2].[MAHCPID] AS [Mahcpid], [t2].[FirstName], [t2].[LastName], [t2].[Gender], [t2].[Address1], [t2].[Address2], [t2].[City], [t2].[State] AS [State], [t2].[ZipCode], [t2].[Email], [t2].[EligStart], [t2].[EligEnd], [t2].[Dependent], [t2].[DateOfBirth], [t2].[ID], [t2].[MiddleInit], [t2].[Age], [t2].[SSN] AS [Ssn], [t2].[County], [t2].[HomePhone], [t2].[EmpGroupID], [t2].[PopulationIdentifier] FROM [dbo].[User] AS [t0] LEFT OUTER JOIN ( SELECT 1 AS [test], [t1].[MAHCPID], [t1].[FirstName], [t1].[LastName], [t1].[Gender], [t1].[Address1], [t1].[Address2], [t1].[City], [t1].[State], [t1].[ZipCode], [t1].[Email], [t1].[EligStart], [t1].[EligEnd], [t1].[Dependent], [t1].[DateOfBirth], [t1].[ID], [t1].[MiddleInit], [t1].[Age], [t1].[SSN], [t1].[County], [t1].[HomePhone], [t1].[EmpGroupID], [t1].[PopulationIdentifier] FROM [dbo].[vwMETRemote] AS [t1] ) AS [t2] ON ([t0].[MAHCPID] = [t2].[MAHCPID]) AND ([t2].[EligEnd] = @p0) WHERE ([t0].[LastName] LIKE @p1) AND ([t0].[DeletedDate] IS NULL) ORDER BY [t0].[LastName], [t0].[FirstName]

    Read the article

  • In SQL Server can I insert multiple nodes into XML from a table?

    - by tpower
    I want to generate some XML in a stored procedure based on data in a table. The following insert allows me to add many nodes but they have to be hard-coded or use variables (sql:variable): SET @MyXml.modify(' insert <myNode> {sql:variable("@MyVariable")} </myNode> into (/root[1]) ') So I could loop through each record in my table, put the values I need into variables and execute the above statement. But is there a way I can do this by just combining with a select statement and avoiding the loop? Edit I have used SELECT FOR XML to do similar stuff before but I always find it hard to read when working with a hierarchy of data from multiple tables. I was hoping there would be something using the modify where the XML generated is more explicit and more controllable.

    Read the article

  • Establishing Upper / Lower Bound in T-SQL Procedure

    - by Code Sherpa
    Hi. I am trying to establish upper / lower bound in my stored procedure below and am having some problems at the end (I am getting no results where, without the temp table inner join i get the expected results). I need some help where I am trying to join the columns in my temp table #PageIndexForUsers to the rest of my join statement and I am mucking something up with this statement: INNER JOIN #PageIndexForUsers ON ( dbo.aspnet_Users.UserId = #PageIndexForUsers.UserId AND #PageIndexForUsers.IndexId >= @PageLowerBound AND #PageIndexForUsers.IndexId <= @PageUpperBound ) I could use feedback at this point - and, any advice on how to improve my procedure's logic (if you see anything else that needs improvement) is also appreciated. Thanks in advance... ALTER PROCEDURE dbo.wb_Membership_GetAllUsers @ApplicationName nvarchar(256), @sortOrderId smallint = 0, @PageIndex int, @PageSize int AS BEGIN DECLARE @ApplicationId uniqueidentifier SELECT @ApplicationId = NULL SELECT @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName IF (@ApplicationId IS NULL) RETURN 0 -- Set the page bounds DECLARE @PageLowerBound int DECLARE @PageUpperBound int DECLARE @TotalRecords int SET @PageLowerBound = @PageSize * @PageIndex SET @PageUpperBound = @PageSize - 1 + @PageLowerBound BEGIN TRY -- Create a temp table TO store the select results CREATE TABLE #PageIndexForUsers ( IndexId int IDENTITY (0, 1) NOT NULL, UserId uniqueidentifier ) -- Insert into our temp table INSERT INTO #PageIndexForUsers (UserId) SELECT u.UserId FROM dbo.aspnet_Membership m, dbo.aspnet_Users u WHERE u.ApplicationId = @ApplicationId AND u.UserId = m.UserId ORDER BY u.UserName SELECT @TotalRecords = @@ROWCOUNT SELECT dbo.wb_Profiles.profileid, dbo.wb_ProfileData.firstname, dbo.wb_ProfileData.lastname, dbo.wb_Email.emailaddress, dbo.wb_Email.isconfirmed, dbo.wb_Email.emaildomain, dbo.wb_Address.streetname, dbo.wb_Address.cityorprovince, dbo.wb_Address.state, dbo.wb_Address.postalorzip, dbo.wb_Address.country, dbo.wb_ProfileAddress.addresstype,dbo.wb_ProfileData.birthday, dbo.wb_ProfileData.gender, dbo.wb_Session.sessionid, dbo.wb_Session.lastactivitydate, dbo.aspnet_Membership.userid, dbo.aspnet_Membership.password, dbo.aspnet_Membership.passwordquestion, dbo.aspnet_Membership.passwordanswer, dbo.aspnet_Membership.createdate FROM dbo.wb_Profiles INNER JOIN dbo.wb_ProfileAddress ON ( dbo.wb_Profiles.profileid = dbo.wb_ProfileAddress.profileid AND dbo.wb_ProfileAddress.addresstype = 'home' ) INNER JOIN dbo.wb_Address ON dbo.wb_ProfileAddress.addressid = dbo.wb_Address.addressid INNER JOIN dbo.wb_ProfileData ON dbo.wb_Profiles.profileid = dbo.wb_ProfileData.profileid INNER JOIN dbo.wb_Email ON ( dbo.wb_Profiles.profileid = dbo.wb_Email.profileid AND dbo.wb_Email.isprimary = 1 ) INNER JOIN dbo.wb_Session ON dbo.wb_Profiles.profileid = dbo.wb_Session.profileid INNER JOIN dbo.aspnet_Membership ON dbo.wb_Profiles.userid = dbo.aspnet_Membership.userid INNER JOIN dbo.aspnet_Users ON dbo.aspnet_Membership.UserId = dbo.aspnet_Users.UserId INNER JOIN dbo.aspnet_Applications ON dbo.aspnet_Users.ApplicationId = dbo.aspnet_Applications.ApplicationId INNER JOIN #PageIndexForUsers ON ( dbo.aspnet_Users.UserId = #PageIndexForUsers.UserId AND #PageIndexForUsers.IndexId >= @PageLowerBound AND #PageIndexForUsers.IndexId <= @PageUpperBound ) ORDER BY CASE @sortOrderId WHEN 1 THEN dbo.wb_ProfileData.lastname WHEN 2 THEN dbo.wb_Profiles.username WHEN 3 THEN dbo.wb_Address.postalorzip WHEN 4 THEN dbo.wb_Address.state END END TRY BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK TRAN EXEC wb_ErrorHandler RETURN 55555 END CATCH RETURN @TotalRecords END GO

    Read the article

  • My VARCHAR(MAX) field is capping itself at 4000; what gives?

    - by eidylon
    Hello all... I have a table in one of my databases which is a queue of emails. Emails to certain addresses get accumulated into one email, which is done by a sproc. In the sproc, I have a table variable which I use to build the accumulated bodies of the emails, and then loop through to send each email. In my table var I have my body column defined as VARCHAR(MAX), seeing as there could be any number of emails currently accumulated for a given email address. It seems though that even though my column is defined as VARCHAR(MAX) it is behaving as if it were VARCHAR(4000) and is truncating the data going into it, although it does NOT throw any exceptions, it just silently stops concatenating any more data after 4000 characters. The MERGE statement is where it is building the accumulated email body into @EMAILS.BODY, which is the field that is truncating itself at 4000 characters. Below is the code of my sproc... ALTER PROCEDURE [system].[SendAccumulatedEmails] AS BEGIN SET NOCOUNT ON; DECLARE @SENTS BIGINT = 0; DECLARE @ROWS TABLE ( ROWID ROWID, DATED DATETIME, ADDRESS NAME, SUBJECT VARCHAR(1000), BODY VARCHAR(MAX) ) INSERT INTO @ROWS SELECT ROWID, DATED, ADDRESS, SUBJECT, BODY FROM system.EMAILQUEUE WHERE ACCUMULATE = 1 AND SENT IS NULL ORDER BY ADDRESS, DATED DECLARE @EMAILS TABLE ( ADDRESS NAME, ALLIDS VARCHAR(1000), BODY VARCHAR(MAX) ) DECLARE @PRVRID ROWID = NULL, @CURRID ROWID = NULL SELECT @CURRID = MIN(ROWID) FROM @ROWS WHILE @CURRID IS NOT NULL BEGIN MERGE @EMAILS AS DST USING (SELECT * FROM @ROWS WHERE ROWID = @CURRID) AS SRC ON SRC.ADDRESS = DST.ADDRESS WHEN MATCHED THEN UPDATE SET DST.ALLIDS = DST.ALLIDS + ', ' + CONVERT(VARCHAR,ROWID), DST.BODY = DST.BODY + '<i>'+CONVERT(VARCHAR,SRC.DATED,101)+' ' +CONVERT(VARCHAR,SRC.DATED,8) +':</i> <b>'+SRC.SUBJECT+'</b>'+CHAR(13)+SRC.BODY +' (Message ID '+CONVERT(VARCHAR,SRC.ROWID)+')' +CHAR(13)+CHAR(13) WHEN NOT MATCHED BY TARGET THEN INSERT (ADDRESS, ALLIDS, BODY) VALUES ( SRC.ADDRESS, CONVERT(VARCHAR,ROWID), '<i>'+CONVERT(VARCHAR,SRC.DATED,101)+' ' +CONVERT(VARCHAR,SRC.DATED,8)+':</i> <b>' +SRC.SUBJECT+'</b>'+CHAR(13)+SRC.BODY +' (Message ID '+CONVERT(VARCHAR,SRC.ROWID)+')' +CHAR(13)+CHAR(13)); SELECT @PRVRID = @CURRID, @CURRID = NULL SELECT @CURRID = MIN(ROWID) FROM @ROWS WHERE ROWID > @PRVRID END DECLARE @MAILFROM VARCHAR(100) = system.getOption('MAILFROM'), DECLARE @SMTPHST VARCHAR(100) = system.getOption('SMTPSERVER'), DECLARE @SMTPUSR VARCHAR(100) = system.getOption('SMTPUSER'), DECLARE @SMTPPWD VARCHAR(100) = system.getOption('SMTPPASS') DECLARE @ADDRESS NAME, @BODY VARCHAR(MAX), @ADDL VARCHAR(MAX) DECLARE @SUBJECT VARCHAR(1000) = 'Accumulated Emails from LIJSL' DECLARE @PRVID NAME = NULL, @CURID NAME = NULL SELECT @CURID = MIN(ADDRESS) FROM @EMAILS WHILE @CURID IS NOT NULL BEGIN SELECT @ADDRESS = ADDRESS, @BODY = BODY FROM @EMAILS WHERE ADDRESS = @CURID SELECT @BODY = @BODY + 'This is an automated message sent from an unmonitored mailbox.'+CHAR(13)+'Do not reply to this message; your message will not be read.' SELECT @BODY = '<style type="text/css"> * {font-family: Tahoma, Arial, Verdana;} p {margin-top: 10px; padding-top: 10px; border-top: single 1px dimgray;} p:first-child {margin-top: 10px; padding-top: 0px; border-top: none 0px transparent;} </style>' + @BODY exec system.LogIt @SUBJECT, @BODY BEGIN TRY exec system.SendMail @SMTPHST, @SMTPUSR, @SMTPPWD, @MAILFROM, @ADDRESS, NULL, NULL, @SUBJECT, @BODY, 1 END TRY BEGIN CATCH DECLARE @EMSG NVARCHAR(2048) = 'system.EMAILQUEUE.AI:'+ERROR_MESSAGE() SELECT @ADDL = 'TO:'+@ADDRESS+CHAR(13)+'SUBJECT:'+@SUBJECT+CHAR(13)+'BODY:'+@BODY exec system.LogIt @EMSG,@ADDL END CATCH SELECT @PRVID = @CURID, @CURID = NULL SELECT @CURID = MIN(ADDRESS) FROM @EMAILS WHERE ADDRESS > @PRVID END UPDATE system.EMAILQUEUE SET SENT = getdate() FROM system.EMAILQUEUE E, @ROWS R WHERE E.ROWID = R.ROWID END

    Read the article

  • Microsoft T-SQL Counting Consecutive Records

    - by JeffW
    Problem: From the most current day per person, count the number of consecutive days that each person has received 0 points for being good. Sample data to work from : Date Name Points 2010-05-07 Jane 0 2010-05-06 Jane 1 2010-05-07 John 0 2010-05-06 John 0 2010-05-05 John 0 2010-05-04 John 0 2010-05-03 John 1 2010-05-02 John 1 2010-05-01 John 0 Expected answer: Jane was bad on 5/7 but good the day before that. So Jane was only bad 1 day in a row most recently. John was bad on 5/7, again on 5/6, 5/5 and 5/4. He was good on 5/3. So John was bad the last 4 days in a row. Code to create sample data: IF OBJECT_ID('tempdb..#z') IS NOT NULL BEGIN DROP TABLE #z END select getdate() as Date,'John' as Name,0 as Points into #z insert into #z values(getdate()-1,'John',0) insert into #z values(getdate()-2,'John',0) insert into #z values(getdate()-3,'John',0) insert into #z values(getdate()-4,'John',1) insert into #z values(getdate(),'Jane',0) insert into #z values(getdate()-1,'Jane',1) select * from #z order by name,date desc

    Read the article

  • sql raiseerror error.number wrong in VB

    - by Melody Friedenthal
    I wrote a T-SQL query which includes a test for valid EmployeeNo. If the EmployeeNo is not valid, I do the following: RAISERROR(5005, 10, 1, N'Invalid Employee No') return @@Error Back in VB.Net I test the sql exception and found that when the Employee No is invalid the error.number is not 5005 as I would expect, but 2732. What is the explanation for this? Thank you.

    Read the article

  • insert into sql table column as GUID

    - by loviji
    I have tried with ado.net create table columnName with unique name. as uniquename I use new Guid() Guid sysColumnName = new Guid(); sysColumnName = Guid.NewGuid(); string stAddColumn = "ALTER TABLE " + tableName + " ADD " + sysColumnName.ToString() + " " + convertedColumnType + " NULL"; SqlCommand cmdAddColumn = new SqlCommand(stAddColumn, con); cmdAddColumn.ExecuteNonQuery(); con.Close(); and it fails: System.Data.SqlClient.SqlException: Incorrect syntax near '-'. ? System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) ? System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) now question, how can i fix it, or how can use different way to create unique column?

    Read the article

  • INSTEAD OF triggers do not support direct recursion

    - by senzacionale
    ALTER TRIGGER [dbo].[TRG_DeleteUser] ON [dbo].[Users] INSTEAD OF DELETE AS BEGIN SET NOCOUNT ON DECLARE @AspNetUserGuid UniqueIdentifier DECLARE @UserId NVARCHAR(36) BEGIN SET @AspNetUserGuid = (SELECT AspNetUserGuid FROM deleted) SET @UserId = (SELECT UserId FROM dbo.Users WHERE AspNetUserGuid = @AspNetUserGuid) IF @AspNetUserGuid IS NOT NULL AND @UserId IS NOT NULL BEGIN EXECUTE [dbo].UsersDelete @AspNetUserGuid, @UserId END END SET NOCOUNT OFF END problem is here: EXECUTE [dbo].UsersDelete @AspNetUserGuid, @UserId i need to call triger before row is actually deleted-

    Read the article

  • Sleep Command in T-SQL?

    - by skb
    Is there to way write a T-SQL command to just make it sleep for a period of time? I am writing a web service asynchronously and I want to be able to run some tests to see if the asynchronous pattern is really going to make it more scalable. In order to "mock" an external service that is slow, I want to be able to call a SQL server with a script that runs slowly, but isn't actually processing a ton of stuff.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >