.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Dynamic SQL query cannot store more than 4000 characters even with NVARCHAR(MAX)

Posted By:      Posted Date: September 08, 2010    Points: 0   Category :Sql Server
Hello, everyone. I am having a rather strange problem when building a dynamic query in SQL Server. I declare a variable of NVARCHAR(MAX) type, and build some queries into it, running them later with sp_executesql. One or two of these queries are so large that they surpass the 4000 char limit that, supposedly, NVARCHAR(MAX) overcomes. However, I still am having the classic problem of storing the whole query inside the variable! I use SQL Server 2008. All the documentation online I checked states that the solution is just using NVARCHAR(MAX) and the problem should not happen. How can this keep happening? Cheers, Ivo Pereira IT Consultant PortugalComputerDoc

View Complete Post

More Related Resource Links

Store and display Japanese characters



Can anyone tell me the best way of storing Japanese characters through ASP.NET.
I have to put characters into a asp:textbox on one page, which saves it to an Access DB.
On a second page I want to display the content in a asp:label.

Should I store the characters directly to the database or should they be encoded, and
how do I encode the characters? 

In my web.config i have:

<globalization fileEncoding="ISO-2022-JP" requestEncoding="ISO-2022-JP" responseEncoding="ISO-2022-JP" culture="ja-JP" uiCulture="ja-JP" />  

On the display page I have:

<meta HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=shift_jis">


How to store binary data as nvarchar(max)?

I’m trying to store a blob of binary data as nvarchar(max) and it gets truncated after just a few bytes. I wonder why and how can I prevent it. I don’t use varbinary(max) because I’m trying to keep existing DB schema intact. Current DB contains a huge chunks of text in nvarchar(max) column and I’m trying to compress (zip) this text and store it back to the same field to reduce DB size.   DB is accessed using Sync Framework (and Entity Framework) on the client side, so actual DB engine is SQL Server Compact 3.5 SP2   Thank you! KonstantinThank you! Konstantin

Dynamic query for Null field checking

Hi I want dynamiclly find the table to null values finding.. Please give me quickly   Regards Ram

Dynamic query for datalength field checking

Hi   Please tell me the dynamic query length in table

Dynamic query for Null field checking

Hi I want dynamically check the data Formation query in SQL server please  provide me the query

Dynamic Class with Linq query Result

Hi, var   query = db.Customers.Where( "City == @0 and Orders.Count >= @1", "London", 10). OrderBy( "CompanyName"). Select( "New(CompanyName as Name, Phone)");    I am using this query as a sample which returns a dynamicclass type, and i need this should to converted to a list collections or datatable etc., As i am holding it in my wcf service with linqtosql as dataaccesslayer. Trying to send the results to the UI which i have consumes this service. Kindly help me in this. Thanks query = db.Customers


Hi Everone,    Can any one help me out in creating a dynamic select statement, so far my SP look like belowALTER PROCEDURE [dbo].[CheckAccess]@TABLENAME VARCHAR(100),@JNID INT=0ASBEGIN    SET NOCOUNT ON;    DECLARE @SQ VARCHAR(500)    DECLARE @ID INT =0     SET @SQ= ' SET @ID = SELECT TOP 1 ID FROM ' +  @TABLENAME + ' WHERE PID ='+ @JNID       PRINT @SQ    EXEC(@SQ)       IF (@ID>0)      BEGIN        RETURN 1      END    ELSE      BEGIN        RETURN 0      ENDENDGOlet me know where i am going wrong

Dynamic Query alternative?

Hi, I was trying to create a query to get some results for next five years and need to show next five years as Column names. So whatever the year user runs this query, it gives the results for the next five years. Then I realized this was not easy as I expected but managed to implement it using Dynamic Queries.I wrote the following code Ito implement that. But I'm not sure is this the best way to do this.   SET ANSI_NULLS ON  GO  SET QUOTED_IDENTIFIER ON  GO  CREATE PROCEDURE sp_RS_ScenariosforNext5Years  @ticker nvarchar(10),  @variable nvarchar(100)  AS  Declare @SQL varchar(1000)  SELECT @SQL = 'SELECT CASE Scenario '  SELECT @SQL = @SQL + ' WHEN ''A'' THEN ''case1'' '  SELECT @SQL = @SQL + 'WHEN ''B'' THEN ''case2'' '  SELECT @SQL = @SQL + 'WHEN ''C'' THEN ''case3'' '  SELECT @SQL = @SQL + 'WHEN ''D'' THEN ''case4'' '  SELECT @SQL = @SQL + 'WHEN ''E'' THEN ''case5'' '  SELECT @SQL = @SQL + 'WHEN ''F'' THEN ''case6'' '  SELECT @SQL = @SQL + 'WHEN ''G''

Dynamic Linq query?

Please excuse my rookiness but is it possible to make a Linq query dynamic in the following pseduo code (to show what I'm trying to do)Dim objCustomoer = (From c In dc.CustomerLocation _ Where c.customerID = a1 _ And { c.zip = a2  OR  c.city = a3  OR  c.state = a4} _                             Select c).ToList() where a2 and a3  and a4 are being populated from user controls and only one will apply.  So query is done by state,  zip or by city, but not by more than one, so the other two would be null.  So the operator is really "OR" but I haven't found anything on a "or" or "whereOr" operator.  How can I accomplish this?

Problems writing a dynamic L2E query

I'm trying to re-work a L2E query to be more dynamic, but I'm not having much luck. Basically, I have two parameters (and many more to come, just laying the foundation), and the parameters are both optional from a user-endpoint.Originally I wrote this static expression:int personnelId = 1234; int divisionId = 1234; var results = (from a in ctx.Attendees from d in a.Divisions join p in ctx.Personnel on a.PersonnelID equals p.PersonnelID where a.PersonnelID == personnelId && d.DivisionID == divisionId select new Attendee { firstName = a.FirstName, lastName = a.LastName });Attendee is a POCO. After I wrote this, I realized that if personnelId or divisionId weren't passed in (or if just one were passed in) I'd want a different result set. I'm conceptualizing the idea like this (doesn't compile, but you get the drift):var results = (from a in ctx.Attendees select new Attendee { firstName = p.FirstName, lastName = p.LastName }); if (personnelId != null) { results = (from a in results join p in ctx.Personnel on a.PersonnelID equals p.PersonnelID where a.PersonnelID == personnelId select a); } if (divisionId != null) { results = (from a in results from d in a.Divisions where d.DivisionID == divisionId select a); } results = results.ToList();Doesn't work well though, because my

How to apply dynamic filter in Datasheet View from Query String

The datasheet view doesn't support either connections/dynamic filters from Query string. How to filter the data using query string?

Parse XML To build Dynamic Query

Hi All, I am trying to figure out the best way to handle a scenario where I will be passed XML that will contain criteria for a search. If the user has selected specific filters then those will be sent in the XML and if there is a section that they left unfiltered then it will not be present in the XML (Which would mean everything for that filter should be returned). My question is around the best process to shred the XML and build a dynamic query out of what i am getting out of the XML object. Is there a better way to handle this scenario? Here is my current approach: Shred the XML and put the filtered data into Global Temp Tables so that I can use them to build my dynamic query. Use those temp tables to create "Where Exists" Criteria within the query to filter down the results based on what was passed to me in XML. If one of the search criteria sections wasn't filtered the temp table would have zero rows and I wouldn't add that to the where clause with an exists statement. I used FOR XML PATH('') in the queries to roll up the data into comma separated values. Build the test schema / objects:   -------------------------------------------------------- --Build Test Schema to demonstrate XML Parsing -------------------------------------------------------- SET NOCOUNT ON; IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[test].[Products]

dynamic table name linq-to-sql query


I am writing a function in which i generate autocode in specific format i want to make this function generalize so that i send tablename and columnname  parameter and function return the next code. I am using linq to sql with MVC e.g. i want to make table name and column name dyanamic

from m in db.<tblnameparam> 
                       orderby m.<colnameparam> descending
                       select m.<colnameparam>

How To Create Dynamic Insert Store Proc


I want to Create a Insert Procedure for Table which has Three Coloum I want to use this Insert Store Proc for another table which has two coloum. If it works then I don't Have to create more Store Proc for Every Table One Insert Proc will Serve my Purpose I am My giving my proc below

Create Proc All_Insert


@Name varchar (30),

@Phone varchar (15)

@Mobile Varchar (15)





insert into Table1














Pivot table query dynamic column.


Hello All,


I want to export my data to excel sheet. The logic to export data in excel is clear.

Now my query is I have 3 tables and I want to generate the data jst like below.



Company Name

Company Email


Create Date


Fax No














And so on.....


The data will come from 3 tables I.e


  1. Master Table for Company

  2. Sort query results by the number of characters matched



    I have a query that takes a multi-word search string and parses it to spit out a LIKE (with AND or OR) condition that I then insert into my dynamic query.

    Example of my parsing:

        'cheese chocolate cake'))),
                                    ' ', ' þ')
                                    , 'þ ',
                                        ''), ' þ'
                        , 'þ'),
                        '%'' OR CakeName LIKE ''%') + '%'')' 

    Say for example that a user searches for the string "cheese chocolate cake". My parsing would result in the following string:

    (c.CakeName LIKE '%CHEESE%' 
    OR CakeName LIKE '%CHOCOLATE%' 
    OR CakeName LIKE '%CAKE%')

    What I wan to do is sort the results based on the number of characters that were actually matched. So, if c.CakeName contained the following:


    • Cheese Cake
    • Chocolate Cake
    • Chocolate Cheese Cake
    • Lemon Cake

    The results would be sorted thusly:

    1. Chocolate Cheese Cake
    2. Chocolate Cake
    3. Cheese Cake
    4. Lemon Cake

Error converting data type nvarchar to numeric in Store Procedure execution



When I execute a Store Procedure via 'EXEC sp_XXX @p1, @p2' I'm getting this error 'Error converting data type nvarchar to numeric'.

After diggin into the TSQL code I have found that there's a field (type: nvarchar(200)) breaking the execution and resulting on the error.

If I query the table and the specified field with the same parameters as the Store Procedure the results are ok! If I execute the same code as the Store Procedure with the same parameters values the results are ok. The error only happens when executing the Store Procedure.

Any idea ?

Thanks in advance,

Gustavo Brian


If I cast the field to a smaller size value, as nvarchar(80), it works, but of course with data truncation.


ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend