473,669 Members | 2,453 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Asignar a una variable el valor de un campo

Hola a todos,

Tengo un problema, no se me ocurre como solucionarlo. Utilizo SQL
Server 2000.
Tengo una tabla (tblRespu) en la que quiero insertar tres valores: el
primero procede de una variable @CodPregunta, el segundo tiene
guardada en texto la información de la columna de otra tabla
(tblPlana) de la que quiero recoger el dato y el tercero es un campo
de esta tabla (tblPlana). No se me ocurre forma de asignarlo, he
probado a crear una variable CHAR asignandole los datos en la forma
(valor1, valor2, valor3), pero da error en el insert porque el numero
de campos no es el mismo que de variables.
Tambien he intentado hacer lo siguiente:

SET @Inserta = ('INSERT INTO tblRespu (CodPregu, CodCues, CodRespu)
SELECT @CodPregunta,' + 'Cuest,'+ @NombrePregunta + 'from
tblPlana')

Para luego hacer EXEC @Inserta, pero al ejecutar he puesto un PRINT
@Inserta y la parte de texto que va detras de la variable
@NombrePregunta no aparece en la variable @Inserta. De todas formas no
estoy segura de que funcionara, porque solo el campo Cuest pertenece a
la tabla tblPlana.

Tampoco puedo insertar los valores uno a uno puesto que en la tabla a
la que inserto los datos (tblRespu) tiene los tres campos como clave.

Alguien puede ayudarme??? Gracias

Saludos. Gema
Jul 23 '05 #1
5 31890
How about using English, punk!?

Uzytkownik "Gema" <ge****@gmail.c om> napisal w wiadomosci
news:53******** *************** ***@posting.goo gle.com...
Hola a todos,

Tengo un problema, no se me ocurre como solucionarlo. Utilizo SQL
Server 2000.
Tengo una tabla (tblRespu) en la que quiero insertar tres valores: el
primero procede de una variable @CodPregunta, el segundo tiene
guardada en texto la información de la columna de otra tabla
(tblPlana) de la que quiero recoger el dato y el tercero es un campo
de esta tabla (tblPlana). No se me ocurre forma de asignarlo, he
probado a crear una variable CHAR asignandole los datos en la forma
(valor1, valor2, valor3), pero da error en el insert porque el numero
de campos no es el mismo que de variables.
Tambien he intentado hacer lo siguiente:

SET @Inserta = ('INSERT INTO tblRespu (CodPregu, CodCues, CodRespu)
SELECT @CodPregunta,' + 'Cuest,'+ @NombrePregunta + 'from
tblPlana')

Para luego hacer EXEC @Inserta, pero al ejecutar he puesto un PRINT
@Inserta y la parte de texto que va detras de la variable
@NombrePregunta no aparece en la variable @Inserta. De todas formas no
estoy segura de que funcionara, porque solo el campo Cuest pertenece a
la tabla tblPlana.

Tampoco puedo insertar los valores uno a uno puesto que en la tabla a
la que inserto los datos (tblRespu) tiene los tres campos como clave.

Alguien puede ayudarme??? Gracias

Saludos. Gema

Jul 23 '05 #2
Gema (ge****@gmail.c om) writes:
Tengo una tabla (tblRespu) en la que quiero insertar tres valores: el
primero procede de una variable @CodPregunta, el segundo tiene
guardada en texto la información de la columna de otra tabla
(tblPlana) de la que quiero recoger el dato y el tercero es un campo
de esta tabla (tblPlana). No se me ocurre forma de asignarlo, he
probado a crear una variable CHAR asignandole los datos en la forma
(valor1, valor2, valor3), pero da error en el insert porque el numero
de campos no es el mismo que de variables.
Tambien he intentado hacer lo siguiente:

SET @Inserta = ('INSERT INTO tblRespu (CodPregu, CodCues, CodRespu)
SELECT @CodPregunta,' + 'Cuest,'+ @NombrePregunta + 'from
tblPlana')


No comprendo por qué usa EXEC() per un INSERT simple. Dice solamente

INSERT INTO tblRespu (CodPregu, CodCues, CodRespu)
SELECT @CodPregunda, Cuest, @NomnrePregunta
FROM tblPlana

In case, ese no es la soluciòn per su problema, por favor incluyer:

o CREATE TABLE por su tablas
o INSERT con ejemplos de datos.
o El result que quiera de esta ejemplos.

I don't understand why you use EXEC() for a simple INSERT. Just say (above).

In this is not the solution of your problem, please post:

o CREATE TABLE statements for your queries.
o INSERT statements with sample data.
o The desired resul given the sample.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #3
pexiak (mp****@poczta. onet.pl) writes:
How about using English, punk!?


How about taking some classes in 1) Spanish(*) 2) Good and polite behaviour?
(*) Hey, according to a list I saw recently, Spanish is now the language
with the second largest number of native speakers, ahead of English.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #4
Hola Erland,

En primer lugar gracias por defender mi idioma. En respuesta a tu
pregunta, el motivo por el que utilizo EXEC para el insert es porque
la variable @NombrePregunta contiene el nombre del campo de la tabla a
la que quiero hacer el INSERT, pero este nombre es variable y lo cojo
de otra tabla. La unica forma que se me ocurrio es esta, si crees que
hay alguna mejor de agradezco mucho si me aconsejas.

Estoy haciendo una aplicación para encuestas, que van a ser importadas
de otro programa que genera un archivo bastante extraño para descifrar
los datos correspondiente s a preguntas, respuestas, .... Utilizo
varias tablas, pero tambien cambio el formato de la tabla, por eso
parece un poco complicado.
Saludos y gracias.
Jul 23 '05 #5

"Gema" <ge****@gmail.c om> wrote in message
news:53******** *************** ***@posting.goo gle.com...
Hola Erland,

En primer lugar gracias por defender mi idioma. En respuesta a tu
pregunta, el motivo por el que utilizo EXEC para el insert es porque
la variable @NombrePregunta contiene el nombre del campo de la tabla a
la que quiero hacer el INSERT, pero este nombre es variable y lo cojo
de otra tabla. La unica forma que se me ocurrio es esta, si crees que
hay alguna mejor de agradezco mucho si me aconsejas.

Estoy haciendo una aplicación para encuestas, que van a ser importadas
de otro programa que genera un archivo bastante extraño para descifrar
los datos correspondiente s a preguntas, respuestas, .... Utilizo
varias tablas, pero tambien cambio el formato de la tabla, por eso
parece un poco complicado.
Saludos y gracias.


El uso de SQL dinámico supone unos riesgos y dificultades particulares, por
lo cual se suele evitarlo a menos que no haya otra posibilidad. Una solución
puede ser CASE:

http://www.hayes.ch/sql/sql_dinamico.html#Dyn_update

Si tienes que importar datos que vienen en un formato difícil, pues piensa
en importarlos en unas tablas intermedias, antes de transformarlos e
insertarlos en las tablas correctas. Así, tus tablas principales quedan
fijas, lo que simplifica tus tareas y consultas normales - las dificultades
residen únicamente en el proceso de importación.

Simon
Jul 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
4550
by: Scott | last post by:
I have an XML Document in a format like: <Variable name="Bob">ABCDEFG</Variable> <Variable name="Steve">QWERTYUI</Variable> <Variable name="John">POIUYTR</Variable> <Variable name="Tim">ZXCVBNM</Variable> <Function id="1"> <Parameter type="String">Bob</Parameter> <Parameter type="String">Steve</Parameter>
4
3243
by: Frederik Sørensen | last post by:
I include a xslt stylesheet with variables for all the error messages in my system. <xsl:variable name="Banner_error_1"> errormessage 1 for banner </xsl:variable> <xsl:variable name="Banner_error_2"> errormessage 2 for banner </xsl:variable>
1
3927
by: Davide | last post by:
Perche' non riesco ad inserire immagini opiu' grandi di 1Mb in un campo LONGBLOB? Ha forse il limite di 1Mb il campo LONGBLOB? Se si, posso modificare tale limite? Per le immagini inferiori a 1Mb e' tutto ok funziona perfettamente. Grazie a tutti, ciao.
0
2066
by: Jorge Gallardo | last post by:
Hola a todos... Vereis, me gustaria saber si se pueden asignar las teclas del F1...al F12, a alguna instruccion dentro de access, ejemplo macro, funcion, consulta. etc etc... Estoy pensando en asignar la tecla de F12, a la funcion Set focus en un formulario para que cada vez que pulse F12, se vaya al campo del foco que le he definido... Alguno sabe si se puede y si es asi, como poder hacerlo...
1
4064
by: g.magliozzi | last post by:
Ciao a tutti, dopo aver copiato dei record tramite una query di accodamento su una tabello ho la necessità di modificare un campo (che risulta vuoto) su tutti i records spostati. Come posso fare? GRAZIE 1000000
1
2818
by: Patricio | last post by:
Buenos días He creado un popup que recibe dos valores, pero este a la vez debe regresar un valor a la página que lo ha llamado. Cómo puedo recuperar éste valor? Gracias
1
8203
by: Neolo | last post by:
Hola, necesito ayuda. Tengo un formulario en access 2003 y necesito hacer que al elegir en un combo la provincia me salga la lista de los municipios de esa provincia, los cuales tengo almacenados en una tabla. Consigo que lo haga si elijo la provincia, cierro el formulario y despues lo vuelvo a abrir, pero necesito que lo haga automaticamente sin tener que cerrar el formulario, y eso no lo consigo, he pensado en ejecutar alguna macro...
15
2787
by: bcochofel | last post by:
Hi, I want to use a variable to sort elements. That var his passed with query string (I'm using Perl CGI to generate XML). Here's a sample of my output: --------------------------------------------- <?xml version="1.0" encoding="iso-8859-1"?> <?xml-stylesheet type="text/xml" href="RR.xsl"?> <!-- $Id: template.xml,v 1.5 2006/12/11 11:13:30 bcochofel Exp $ --> <RR xmlns:xsi="http://www.w3.org/2001/XMLSchema"...
0
1528
by: =?Utf-8?B?Z2FtYmluaQ==?= | last post by:
Hola a los miembros de la comunidad. Voy a exponer un caso que me está sobrecalentando los circuitos. Seguramente interesará a muchos. Mi objetivo es recuperar el último Id de la tabla proyectos(Id del último registro). Estoy trabajando con VS 2008 y SQL 2005. Vamos al punto, muestro el código. Tabla proyectos Campos(columnas):IdProyecto, nombre, sector, pais, comentario, fecha Store procedure ALTER PROCEDURE .
0
8465
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8895
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8809
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8588
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5682
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4386
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2797
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2032
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1788
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.