Pass NVARCHAR (or Other String-type) Var As A Column Or Table Name In SQL
Jun 21, 2004
Hey folks, the question is fairly simple, unfortunately the answer has proven rather elusive.
Is it possible to declare a variable which would then be used to identify either a column or table in an SQL statement?
Here's a basic idea of what I'd like to do:
DECLARE @myVar AS NVARCHAR(50)
SELECT *
FROM @myVar
or
DECLARE @myVar AS NVARCHAR(50)
SELECT @myVar
FROM MyTable
I'm probably looking for some sort of built in function that will accept an argument here... like COLUMN(@myVar) or something of the like. I just don't know where to look...
I have a stored procedure that contains a paramteter of type nvarchar(max). What is the syntax to pass this parameter to the sp from a VB.Net application. Specifically, I need to know what to put in the 3rd parameter below:
Problem about pass a big string (over 8000 characters) to a variable nvarchar(max) in stored procedure in SQL 2005! I know that SQL 2005 define a new field nvarchar(max) which can stored 2G size string. I have made a stored procedure Hellocw_ImportBookmark, but when I pass a big string to @Insertcontent , the stored procedure can't be launch! why? create procedure Hellocw_ImportBookmark @userId varchar(80), @FolderId varchar(80), @Insertcontent nvarchar(max) as declare @contentsql nvarchar(max); set @contentsql=N'update cw_bookmark set Bookmark.modify(''declare namespace x="http://www.hellocw.com/onlinebookmark"; insert '+ @Insertcontent+' as last into (//x:Folder[@Id="'+@FolderId+'"])[1]'') where userId='''+@userID+''''; exec sp_executesql @contentsql;
as declare @contentsql nvarchar(max); set @contentsql=N'update cw_bookmark set Bookmark.modify(''declare namespace x="http://www.hellocw.com/onlinebookmark"; insert '+ @Insertcontent+' as last into (//x:Folder[@Id="'+@FolderId+'"])[1]'') where userId='''+@userID+''''; exec sp_executesql @contentsql;
Hi, I want to add a newline in a content of sql column (using t-sql and not asp.net textbox) so when content is being rendered in a .net textbox I get separate rows, so insteadcol1 col2 col3 I woule like to havecol1col2col3Thanks
Hi, I have a webform with a drop-down listbox, binded to a table and a GridView, binded to another table. My goal is when I select a value (country in my case) in the drop-down listbox to change what is shown in the GridView, based on the ID that I get from the drop-down listbox. Here is the code (the important parts...): Select a Country : <asp:DropDownList ID="CountriesDropDownList" runat="server" DataSourceID="SqlDataSource2" DataTextField="Name" DataValueField="CountryID" Width="220px" AutoPostBack="True"> </asp:DropDownList> <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" SelectCommand="SELECT [CountryID], [Name] FROM [DS_Country]"> </asp:SqlDataSource> <asp:GridView ID="ProvincesGridView" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ProvinceID,CountryID,Name,ShortName,Description" DataSourceID="SqlDataSource1" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" HorizontalAlign="Left" > <Columns> .............................. </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DineSelectConnectionString %>" DeleteCommand="DELETE FROM DS_Province WHERE ProvinceID=@ProvinceID" SelectCommand="SELECT ProvinceID,CountryID,Name,ShortName,Description FROM DS_Province WHERE CountryID=@ddlCountryID" UpdateCommand="UPDATE DS_Province SET CountryID=@CountryID,Name=@Name,ShortName=@ShortName,Description=@Description WHERE ProvinceID=@ddlCountryID" InsertCommand="INSERT INTO DS_Province (CountryID,Name,ShortName,Description) VALUES (@CountryID,@Name,@ShortName,@Description)"> <SelectParameters> <asp:ControlParameter Name="ddlCountryID" ControlID="CountriesDropDownList" PropertyName="DataValueField" /> </SelectParameters> </asp:SqlDataSource>
When I run it I get this error "Syntax error converting the nvarchar value 'CountryID' to a column of data type int.". If I specify the Type="Int" in <asp:ControlParameter>..</> I get "Input string was not in a correct format. " This is supposed to be easy, but I can't make it work ! Any suggestions will be more than welcome. Thanks.
I am reading data from another data source and storing it in the sqlce database. Some of the string values I'm trying to insert into the database have single quotes in the string (i.e. Johnny's Company). When I try to insert the values with the single quotes, it throws an exception. The code I use to insert the records is as follows:
cmd.CommandText = "INSERT sy_company " +
" (company_id, company, co_name, companyid) " +
"VALUES(" +
"'" + dtSYCompany.Rows[x]["company_id"] + "'," +
"N'" + dtSYCompany.Rows[x]["company"] + "'," +
"N'" + dtSYCompany.Rows[x]["co_name"] + "'," +
"'" + dtSYCompany.Rows[x]["companyid"] + "')";
cmd.ExecuteNonQuery();
When the company name (co_name) has a single quote in it, I get the error. How do I write the insert statement so it will work even though the value being inserted into co_name has a single quote in it?
Hi, all I'm getting this error at runtime when my page tries to populate a datagrid. Here's the relevant code. First, the user selects his choice from a dropdownlist, populated with a sqldatasource control on the aspx side:<asp:SqlDataSource ID="sqlDataSourceCompany" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [PayrollCompanyID], [DisplayName] FROM [rsrc_PayrollCompany] ORDER BY [DisplayName]"> </asp:SqlDataSource> And the dropdown list's code:<asp:DropDownList ID="ddlPayrollCompany" runat="server" AutoPostBack="True" DataSourceID="sqlDataSourcePayrollCompany" DataTextField="DisplayName" DataValueField="PayrollCompanyID"> </asp:DropDownList> Then, I use the selectedindexchanged event to bind the data to the datagrid. Here's that code: 1 Sub BindData() 2 3 Dim ds As New DataSet 4 Dim sda As SqlClient.SqlDataAdapter 5 Dim strSQL As String 6 Dim strCon As String 7 8 strSQL = "SELECT [SocialSecurityNumber], [Prefix], [FirstName], [LastName], [HireDate], [PayrollCostPercent], " & _ 9 "[Phone], [BadgeNumber], [IsSupervisor], [SupervisorID], [IsUser], [IsScout] FROM [rsrc_Personnel] " & _ 10 "WHERE ([PayrollCompanyID] = @PayrollCompanyID)" 11 12 strCon = "Data Source=DATASOURCE;Initial Catalog=DATABASE;User ID=USERID;Password=PASSWORD" 13 14 sda = New SqlClient.SqlDataAdapter(strSQL, strCon) 15 16 sda.SelectCommand.Parameters.Add(New SqlClient.SqlParameter("@PayrollCompanyID", Me.ddlPayrollCompany.SelectedItem.ToString())) 17 18 sda.Fill(ds, "rsrc_Personnel") 19 20 dgPersonnel.DataSource = ds.Tables("rsrc_Personnel") 21 dgPersonnel.DataBind() 22 23 End Sub 24
I'm assuming my problem lies in line 16 of the above code. I've tried SelectedItemIndex, SelectedItemValue too and get errors for those, as well. What am I missing? Thanks for anyone's help! Cappela07
I have SQL Server 2012 SSIS. I have Excel source and OLE DB Destination.I have problem with importing CustomerSales column.CustomerSales values like 1000.00,2000.10,3000.30,NotAvailable.So I have decimal values and nvarchar mixed in on Excel column. This is requirement for solution.However SSIS reads only numeric values correctly and nvarchar values are set as Null. Why?
I'm still plunking away on a history trigger that requires the evaluation of whether or not each column has been updated. If it has,t hen I'll be tossing a record into a history table.
Basically I need something to function along the same logic as this:
IF UPDATED(@s) BEGIN --some code END
Any thoughts you folks may have are greatly appreciated.
INSERT INTO #Activities VALUES('Field phase S14-04932-01') INSERT INTO #Activities VALUES('Phase reporting') INSERT INTO #Activities VALUES('Phase running') INSERT INTO #Activities VALUES('RD1')
I am Using Derived column between Source and Destination Control. the Source input column PriceTime is String Data type. but in the Destination is should be a DATE TIME column. How to Convert this string to DateTime in the Derivied Column Control.
I already tried to in the Derived column control
PRICEDATETIME <add as new column> ((DT_DBTIMESTAMP)priceDateTime) database timestamp [DT_DBTIMESTAMP]
But still throwing Error showing type case probelm
Hi guys, If I have a temporary table called #CTE With the columns [Account] [Name] [RowID Table Level] [RowID Data Level] and I need to change the column type for the columns: [RowID Table Level] [RowID Data Level] to integer, and set the column [RowID Table Level] as Identity (index) starting from 1, incrementing 1 each time. What will be the right syntax using SQL SERVER 2000?
I am trying to solve the question in the link below: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2093921&SiteID=1
Thanks in advance, Aldo.
I have tried the code below, but getting syntax error...
ALTER TABLE #CTE ALTER COLUMN [RowID Table Level] INT IDENTITY(1,1), [RowID Data Level] INT;
I have also tried:
ALTER TABLE #CTE MODIFY [RowID Table Level] INT IDENTITY(1,1), [RowID Data Level] INT;
Hi everybody,I'm using SQL Server Management Studio Express.I'm trying to create a field which contains a text entered by the user. So, it should be able to contain at least 500 characters.I used the type "nvarchar(MAX)". The problem is that the type contains about 50 characters max!!I couldn't find out where and how to fix that. If you have any idea :)Thanks a lot
can anyone help me figure out why when i run the following storedprocedure i get the error:(1460 row(s) affected)Msg 245, Level 16, State 1, Procedure SP_SALESTRENDS, Line 40Conversion failed when converting the varchar value 'X' to data typeint.SP:--STORED PROCEDURE FOR INVOICE TRENDS:--To use Stored Procedure use the following code:--EXEC SP_INSPECTIONSUMRY (MONTH), (OFFICE)--(OFFICE) CAN BE: BGR FOR BANGOR, SP FOR SOUTH PORTLAND, NH FOR NEWHAMPSHIRE, UNH FOR UNH--(REPORT) CAN BE: PRODUCT CODE FOR REPORT BROKEN OUT BY PRODUCT CODE-- EXEC SP_SALESTRENDS BGR, INVOICED, 2006, XALTER PROCEDURE SP_SALESTRENDS@OFFICE VARCHAR(30),@REPORT VARCHAR(30),@VARYEAR INT,@CODE VARCHAR(30)ASIF @REPORT='INVOICED'SELECT YEAR(I.INVOICEDAT) AS VARYEAR, MONTH(I.INVOICEDAT) AS VARMONTH,SUM(I.STOTAL) AMOUNT, P.PERSON, P.PRODUCT, C.DESCRIPTNINTO #TEMP_SALESTRENDSFROM OPENQUERY(PROJECTS, 'SELECT PROJECT, INVOICEDAT, STOTALFROM INVSUMYR') ILEFT JOIN(SELECT *FROM OPENQUERY(PROJECTS, 'SELECT NUMBER, PRODUCT, PERSONFROM PROJMAST')) PON (LTRIM(I.PROJECT)=LTRIM(P.NUMBER))LEFT JOIN(SELECT PC, DESCRIPTNFROM OPENQUERY(PROJECTS, 'SELECT PC, DESCRIPTNFROM PRODCODE')) CON (C.PC=P.PRODUCT)GROUP BY YEAR(I.INVOICEDAT), MONTH(I.INVOICEDAT), P.PERSON, P.PRODUCT,C.DESCRIPTNORDER BY VARYEAR, VARMONTH-- INVOICED REPORT BROKEN OUT BY OFFICEIF @REPORT='INVOICED' AND @CODE=1 AND @VARYEAR=1234 AND@OFFICE='NORRIS'SELECT VARYEAR , VARMONTH , SUM(AMOUNT) AS AMOUNTFROM #TEMP_SALESTRENDSGROUP BY VARYEAR, VARMONTHORDER BY VARYEAR, VARMONTHIF @REPORT='INVOICED' AND @CODE!=1 AND @VARYEAR=1234SELECT VARYEAR, VARMONTH, SUM(AMOUNT) AS AMOUNTFROM #TEMP_SALESTRENDSWHERE PRODUCT=@CODEGROUP BY VARYEAR, VARMONTHORDER BY VARYEAR, VARMONTHIF @REPORT='INVOICED'AND @CODE!=1 AND @VARYEAR!=1234SELECT VARYEAR , VARMONTH , SUM(AMOUNT) AS AMOUNTFROM #TEMP_SALESTRENDSWHERE PRODUCT=@CODE AND VARYEAR=@VARYEARGROUP BY VARYEAR, VARMONTHORDER BY VARYEAR, VARMONTHIF @REPORT='INVOICED' AND @OFFICE='NORRIS' AND @CODE=1 AND@VARYEAR!=1234SELECT VARYEAR , VARMONTH , SUM(AMOUNT) AS AMOUNTFROM #TEMP_SALESTRENDSWHERE VARYEAR=@VARYEARGROUP BY VARYEAR, VARMONTHORDER BY VARYEAR, VARMONTHIF @REPORT='INVOICED' AND @OFFICE='BGR' AND @CODE=1 AND @VARYEAR=1234SELECT VARYEAR , VARMONTH , SUM(AMOUNT) AS AMOUNTFROM #TEMP_SALESTRENDSWHERE PRODUCT IN ('G', 'H', 'I', 'J', 'K', 'L')GROUP BY VARYEAR, VARMONTHORDER BY VARYEAR, VARMONTHIF @REPORT='INVOICED' AND @OFFICE='BGR' AND @CODE=1 AND @VARYEAR!=1234SELECT VARYEAR , VARMONTH , SUM(AMOUNT) AS AMOUNTFROM #TEMP_SALESTRENDSWHERE PRODUCT IN ('G', 'H', 'I', 'J', 'K', 'L') AND VARYEAR=@VARYEARGROUP BY VARYEAR, VARMONTHORDER BY VARYEAR, VARMONTHIF @REPORT='INVOICED' AND @OFFICE='SP' AND @CODE=1 AND @VARYEAR=1234SELECT VARYEAR , VARMONTH , SUM(AMOUNT) AS AMOUNTFROM #TEMP_SALESTRENDSWHERE PRODUCT IN ('A', 'B', 'C', 'D', 'E', 'C', 'S', '3', '4')GROUP BY VARYEAR, VARMONTHORDER BY VARYEAR, VARMONTHIF @REPORT='INVOICED' AND @OFFICE='SP' AND @CODE=1 AND @VARYEAR!=1234SELECT VARYEAR , VARMONTH , SUM(AMOUNT) AS AMOUNTFROM #TEMP_SALESTRENDSWHERE PRODUCT IN ('A', 'B', 'C', 'D', 'E', 'C', 'S', '3', '4') ANDVARYEAR=@VARYEARGROUP BY VARYEAR, VARMONTHORDER BY VARYEAR, VARMONTHIF @REPORT='INVOICED' AND @OFFICE='NH' AND @CODE=1 AND @VARYEAR=1234SELECT VARYEAR , VARMONTH , SUM(AMOUNT) AS AMOUNTFROM #TEMP_SALESTRENDSWHERE PRODUCT IN ('W', 'X', 'Y', 'N', 'O', 'P')GROUP BY VARYEAR, VARMONTHORDER BY VARYEAR, VARMONTHIF @REPORT='INVOICED' AND @OFFICE='NH' AND @CODE=1 AND @VARYEAR!=1234SELECT VARYEAR , VARMONTH , SUM(AMOUNT) AS AMOUNTFROM #TEMP_SALESTRENDSWHERE PRODUCT IN ('W', 'X', 'Y', 'N', 'O', 'P') AND VARYEAR=@VARYEARGROUP BY VARYEAR, VARMONTHORDER BY VARYEAR, VARMONTHIF @REPORT='INVOICED' AND @OFFICE='UNH' AND @CODE=1 AND @VARYEAR=1234SELECT VARYEAR , VARMONTH , SUM(AMOUNT) AS AMOUNTFROM #TEMP_SALESTRENDSWHERE PRODUCT IN ('U', 'Z', 'R', 'V')GROUP BY VARYEAR, VARMONTHORDER BY VARYEAR, VARMONTHIF @REPORT='INVOICED' AND @OFFICE='UNH' AND @CODE=1 AND @VARYEAR!=1234SELECT VARYEAR , VARMONTH , SUM(AMOUNT) AS AMOUNTFROM #TEMP_SALESTRENDSWHERE PRODUCT IN ('U', 'Z', 'R', 'V') AND VARYEAR=@VARYEARGROUP BY VARYEAR, VARMONTHORDER BY VARYEAR, VARMONTH--END OF SALES TRENDS STORED PROCEDUREthanks.
Hi All I want to retrieve the data type of table column and validate the input data whether same as data type of table column before insert into database. Any suggestion? I use asp.net + msde
nvarchar(max) I have a nvarchar(MAX) “Description” field in my SQL Server 2005 database. Somewhere I think I read that nvarchar(MAX) is the size of 4000. My question is in my Insert Stored Proc set ANSI_NULLS ONset QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[syl_CodeScheduleTypeInsert] @ScheduleName nvarchar(50), @ScheduleDescription nvarchar(????????)ASBEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; BEGIN TRY INSERT I What number should replace the ???????? with? nvarchar(4000) is that correct? I tried nvarchar(MAX) and nvarchar but both versions only input one character into my database table. Please help a newbie out, cheers!
Hi i keep getting this error when i search based on Team name (dropdownlist) or coach name(textbox). However it works when i make the search based on the region id(dropdownlist) here is my stored procedure;ALTER PROCEDURE [dbo].[stream_FindTeam] -- Add the parameters for the stored procedure here @coachName varchar(100), @TeamName varchar(100),@regionID INT
AS SELECT TeamID, coachName FROM Teams WHERE coachName LIKE @coachName OR TeamName= @TeamNameOR regionID = @regionID; Here is my code;SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["streamConnectionString"].ConnectionString); conn.Open();SqlCommand command = new SqlCommand("stream_FindTeam", conn); command.CommandType = CommandType.StoredProcedure;command.Parameters.AddWithValue("@coachName", coachName.Text); command.Parameters.AddWithValue("@TeamName", TeamList.SelectedValue);command.Parameters.AddWithValue("@regionID", Region.SelectedValue);SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); DataList1.DataSource = reader; DataList1.DataBind(); conn.Close();
I recently upsized my acess 2000 db to SQL 2000, but I am now having errors . . .
Error Type: Microsoft OLE DB Provider for ODBC Drivers (0x80040E07) [Microsoft][ODBC SQL Server Driver][SQL Server]The sum or average aggregate operation cannot take a nvarchar data type as an argument. /data_count.asp, line 4
The code within the asp file: <% dataSQL = "SELECT SUM(filesize) FROM DL where show=1" Set datacount = my_Conn.Execute(dataSQL) anBytes = datacount(0) %>
I want to create a table. One of the columns should be in the data type MONEY with two digits on the right side of the decimal point. How is that possible?
How would I best go about changing a published table's column from smallint to int? I could not find anything about it in BOL or MS.com. I do not think EM/Replication Properties allows the change. I suspect I have to run "Alter Table/Column" on the Publisher and each Subscriber the old-fashioned way. Is that true?
I am using SQL Server 2000 Enterprise Edition fully patched. Database is in Simple Recovery mode.
I need to change a column's data type from "int(4)" to "smallint(2)". I know for sure that there will be no data (precision) lost, because I know the possible values that this column could have.
My problem is that the table I am dealing with has 600,000,000 records in it. I dropped all indexes before I tried to alter the table. But still it is taking forever and filling up my 280GB disk with transaction log file.
I know that in Oracle, if I want I can turn off logging and do these kind of modifications relatively faster.
I was wondering if there is a way of disabling logging before running this alter command.
What is the best practice to handle a situation of this sort?
I uploading an image from a web page into Sql Server 2000 database. I call a stored procedure with the parameter @Flag of type Image. When I tried to pass a null value to this parameter I got the error:"Operand type clash: nvarchar is incompatible with image".I was adding the parameter like this:sqlCmd.Parameters.AddWithValue("@Flag", DBNull.Value);After trying few different things I found a workaround using the following:sqlCmd.Parameters.Add("@Flag", SqlDbType.Image);sqlCmd.Parameters["@Flag"].Value = DBNull.Value;Possibly a bug in the SqlCommand.Parameters.AddWithValue method ?
I getting the above error can someone please help me solve it, here is the code: public void InsertHost() { // TODO // - Call stored procedure to write to a log file writeToLog using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"])) { SqlCommand cmd = new SqlCommand("writeToLog", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@pAction", "action"); cmd.Parameters.AddWithValue("@pHostName", "Hostname"); cmd.Parameters.AddWithValue("@pUserNUm", "requestorID"); cn.Open(); cmd.ExecuteNonQuery(); } } Here is the storedprocedure: ALTER PROCEDURE dbo.writeToLog(@pAction varchar(10), @pUserNUm bigint, @pHostName varchar(25))AS INSERT INTO dbo.hostNameLog (action, requestorID, HostName)VALUES (@pAction, @pUserNUm, @pHostName) Here is the table: HostName - varchar, action - varchar, requestorID - bigint I can't seem to find the error.
Hi I have an insert stored procedure with a parameter @eventDate date type date time. I have written a web form that takes the textbox.text value and assigns to the @eventDate parameter using a querystring. Howevr when I run the application I get a SQL Exception error converting data type nvarchar to datetime. I have tried dssqlInsertEvent.InsertParameters.add("EventDate", convert.todatetime(txtEventDate.text)); wbut received another error. Any assistance would be greatly appreciated.