Category Archives: Software

seleccionar registro de una tabla y 1 solo registro relacionado / select records from a table and only 1 related record.


Por ejemplo que tenemos una tabla de artículos y una tabla de códigos de barra relacionados con dicho artículo y necesitamos por cada artículo 1 solo código de barra porque con esto sabremos si tiene barra o no y no requerimos todos los códigos de barra.  / For example we have an articles table and barcodes table, we need for each article show just 1 barcode that will show that the article has barcode no matter how many.

Estas serían las tablas / example tables:


create table #tmpartic(codigo varchar(10), nombre varchar(50))
insert into #tmpartic values('001', 'KEYBOARD / TECLADO')
insert into #tmpartic values('002', 'MOUSE / RATON')
insert into #tmpartic values('003', 'PEN / LAPICERO')
insert into #tmpartic values('004', 'DISPLAY / MONITOR')
insert into #tmpartic values('005', 'HARD DISK / DISCO DURO')


create table #tmpbars(article varchar(10), codbar varchar(20))
insert into #tmpbars values('001', '8909001212')
insert into #tmpbars values('001', '8909001213')
insert into #tmpbars values('001', '8909001214')
insert into #tmpbars values('003', '8909051223')
insert into #tmpbars values('004', '8909061245')
insert into #tmpbars values('005', '8909071241')

Ahora vamos a seleccionar con un left normal / select with a normal “left” query :

select art.codigo, art.nombre, isnull(bar.codbar,'') as codbar from #tmpartic art left join #tmpbars bar on art.codigo=bar.article

Esto nos retorna todos los registros repetidos artículos en barras, se puede ver el artículo 001 que se repite 3 veces / this is returning 3 repeated records of the article 001:

repetidos

Ahora veamos la magia, vamos a usar la instrucción que nos retornará solo 1 registro relacionado / Now let’s watch the magic, with this instruction we will have only 1 related record:

select art.codigo, art.nombre, isnull(bar.codbar,'') as codbar from #tmpartic art outer apply(select top 1 article, codbar from #tmpbars where article=art.codigo) bar

Resultado, no se repiten los registros de barras y sale solo 1 barra / This is the result, just 1 barcode for each article:

repetidos_no

Podemos usar este sql cuando necesitamos filtrar repetidos desde la misma ejecución de la sentencia SQL. / We can use this sql when we need to filter repeated records since the start of the Sql sentence.

 

 

Huawei a volar? Huawei to fly?


Que creen que va a pasar con Huawei? acaso no se acuerdan que cuando las dificultades llegan las mejores respuestas aparecen? Huawei de seguro tiene todo listo para responder, pero no lo hacían porque no había necesidad….. ya apareció la necesidad. Google y usa es su culpa, el gigante va a crecer más ahora.

What you think about Huawei? don’t you remember when difficulties arrives the best things will appear? Huawei for sure have everything ready to answer. But they never did anything like that because they weren’t needing that, now, it’s different. Google and usa is your fault, the giant is going to grow now…

huawei-china-5g

Filas a Columnas SQL Server / Rows to Cols in SQL Server


Tenemos una consulta de 4 columnas y las 2 primeras las necesitamos tal como se ven pero de las 2 siguientes la 3ra la necesitamos como columnas según el contenido que tenga y la cuarta como los datos que van en dicha nueva columna. De tal forma que si en la 3ra columna hay 3 o 5 diferentes datos, se crearán 3 o 5 nuevas columnas. A continuación unos datos de ejemplo para entender bien el proceso. / We have 4 Cols and the first 2 we need them exactly as they are, but the next 2 this way, the third must be new colum as different value it has, the fourth is the data for the columns created by the third one. Now this is an example to understand better this process:


create table #tmpartic(codigo varchar(10), nombre varchar(50))
create table #tmpartic_idi(artic varchar(10), idioma varchar(3), traducc varchar(50))
create table #tmpidioma(codigo varchar(3), nombre varchar(50))


insert into #tmpidioma values('ENG', 'ENGLISH')
insert into #tmpidioma values('CAT', 'CATALÀ')
insert into #tmpidioma values('FRE', 'FRENCH')


insert into #tmpartic values('001', 'HELADO DE VAINILLA')
insert into #tmpartic values('002', 'HELADO DE CHOCOLATE')
insert into #tmpartic values('003', 'MALTEADA DE FRESA')
insert into #tmpartic values('004', 'TORTA DE QUESO')
insert into #tmpartic values('005', 'CREMA BATIDA')


insert into #tmpartic_idi values('001','ENG', 'VANILLA ICE CREAM')
insert into #tmpartic_idi values('001','CAT', 'GELAT DE VAINILLA')
insert into #tmpartic_idi values('001','FRE', 'GLACE À LA VANILLE')
insert into #tmpartic_idi values('002','ENG', 'CHOCOLATE ICE CREAM')
insert into #tmpartic_idi values('002','CAT', 'GELAT DE XOCOLATA')
insert into #tmpartic_idi values('002','FRE', 'GLACE AU CHOCOLAT')
insert into #tmpartic_idi values('003','ENG', 'STRAWBERRY SHAKE')
insert into #tmpartic_idi values('003','CAT', 'MALTAT DE MADUIXA')
insert into #tmpartic_idi values('003','FRE', 'FRAISE MALTE')
insert into #tmpartic_idi values('004','ENG', 'CHEESECAKE')
insert into #tmpartic_idi values('004','CAT', 'COCA DE FORMATGE')
insert into #tmpartic_idi values('004','FRE', 'GÂTEAU AU FROMAGE')
insert into #tmpartic_idi values('005','ENG', 'WHIPPED CREAM')
insert into #tmpartic_idi values('005','CAT', 'CREMA BATUDA')
insert into #tmpartic_idi values('005','FRE', 'CRÈME FOUETTÉE')

--esta es la consulta normal que nos muestra las traducciones por cada artículo un dato interesante "article" es la misma palabra para catalán, inglés y francés.
--this is the normal query to bring all the translations for each article by the way "article" is the same word in the 3 languages
select A.CODIGO, A.NOMBRE, C.NOMBRE as IDIOMA, B.TRADUCC
from #tmpartic A
join #tmpartic_idi B on A.CODIGO=B.ARTIC
join #tmpidioma C on B.IDIOMA=C.CODIGO

Esta consulta muestra todos los artículos con cada traducción en estilo filas. / This query is showing all the articles with each traduction in row style:

Resultado Normal
Normal resultset, we want to change the IDIOMA data to cols

--ahora, aquí está la magia, nosotros le decimos al sql server que le proporcionaremos los nombres de columnas en la variable @cols
--now, here is the magic, we are telling sql server that we will provide the column names in the @cols variable
--then we will query the data with the dynamic result for the columns.
declare @cols as nvarchar(4000), @query as nvarchar(4000)
select @cols=STUFF((select ',' + quotename(RTRIM(NOMBRE))
from #tmpidioma group by nombre for xml path(''),type).value('.', 'varchar(4000)'),1,1,'')
--print @cols
set @query= N'select codigo,nombre,'+@cols+ N' from (
select A.CODIGO, A.NOMBRE, C.NOMBRE as IDIOMA, B.TRADUCC
from #tmpartic A
join #tmpartic_idi B on A.CODIGO=B.ARTIC
join #tmpidioma C on B.IDIOMA=C.CODIGO
where 1=1
) P PIVOT(
max(traducc) for idioma in ('+@cols+N')
) as pivot_table '
--print @query
exec sp_executesql @query

Y este es el resultado final. / This is the final result:

Resultado Esperado
Resultset rows to cols

Todo se puede hacer en un script sql, pero también se puede crear un stored procedure. Depende de para que necesite utilizar este proceso. / You can do this in a script sql file, but also you can create a stored procedure. It depends on the requirement that you are working on.

Listar todos los stored procedures en SQL SERVER


Para cuando necesitamos saber que tantos SPs hay en un servidor de SQL Server / If you need to find all the SPs in a SQL Server:

create table #temptable(bd varchar(50) null, name varchar(150) null, object_id integer null, modify_date datetime null)

use master
execute sp_MSforeachdb ‘use [?];insert into #temptable select ”?”,name, object_id, modify_date from sys.procedures’

select * from #temptable

Tenga en cuenta que esto puede durar varios minutos dependiendo del tamaño del SQL Server. / Note that running time of this maybe take several minutes depending on the SQL Server Size.

Object reference not set to an instance of an object. Visual Studio C++ Project.


Object reference not set to an instance of an object. When compiling a C++ Project.

This means something is not working due compiler is missing or trying to use some extensions that are not ready to use. To check this open Visual Studio in Safe Mode by running it with devenv /safemode, then reopen the project and build it again.

If the project is now building ok, you can reset settings in your dev environment by clicking “Tools->Import and Export Settings” then choosing “Reset all settings”.

To run Visual Studio in Safe Mode the easy way is to add the parameter /safemode in the shortcut of the App. For this start by right click on the icon app, on Visual Studio right click again, then choose properties:

safemode0

Add the parameter at the end of the target expression:

safemode00

Now when you click on the App icon it must be run on “Safe Mode”

safemode1

After you check that its working, modify again the shortcut to eliminate the “/safemode” parameter to continue using your Visual Studio in normal mode.

 

You can do this on command window too, open a new cmd window then go to the directory of the devenv.exe file and there write the command “devenv,exe /safemode”

safemode2

 

your virus and threat protection is managed by your organization


Si le sale este mensaje en su windows defender y no está vinculado a un antivirus empresarial, probablemente un programa malware lo ha deshabilitado en el registro. Para corregir abra una ventana de comandos en modo administrador y ejecute este comando:

REG DELETE “HKLM\SOFTWARE\Policies\Microsoft\Windows Defender” /v DisableAntiSpyware

Responder Yes y enter para proceder. Luego dar clic derecho sobre el ícono de windows defender y escoger Quick Scan. Si no aparece reiniciar el computador. Y al abrir de nuevo el windows defender activar la protección si es requerido.

Windows Protegió su PC o desbloquear archivos bloqueados en Windows


Cuando descargamos archivos y especialmente si son ejecutables, windows puede poner una marca para bloquearlo. Esto puede causar problemas para ejecutar los archivos. Si no se ejecutan los archivos como deberían, podemos comprobar si están bloqueados dando clic derecho sobre el archivo, propiedades, se ve un mensaje que dice que como el archivo proviene de otro equipo se podría bloquear, que es lo que hará siempre. Si damos clic en “Desbloquear” queda listo este archivo. Pero que sucede si son cientos de archivos en varios directorios?

Bloq
Archivo Bloqueado por Windows

 

 

 

 

En ese momento debemos usar el PowerShell de windows:

con el comando:

C:\descargas> dir .\directorio_descargados -Recurse | Unblock-File

Se puede o no mostrar un listado de los archivos que se van desbloqueando y al final ya quedan todos los archivos listos sin la marca de seguridad de bloqueo.

Unblock
Desbloqueo Masivo de archivos por directorio

 

 

 

 

Esta opción permite desbloquear todos los archivos contenidos dentro del directorio descargas.

Error en la llamada a procedimiento remoto. [0x800706be]


Este error me salió luego de instalar el SQL SERVER 2014 sobre una máquina donde ya tenía previamente SQL SERVER 2008R2, al abrir el Sql Server Configuration Manager sale este error:

error-sql-server-2014-configuration-manager

El problema es que se está abriendo el configurador del viejo 2008, se debe abrir el configurador para SQL SERVER 2014, de otra forma seguirán viendo el error.

Al abrir el Sql Server Configuration Manager del 2014 ya aparecerán bien todas las instancias:

sql-server-configuration-manager-2014

SQL Server uptime / Tiempo de actividad


There is a small sql command to know SQLServer Uptime, open your SSMS, open a new Query Window and paste this, press F5 and watch:

SELECT sqlserver_start_time FROM sys.dm_os_sys_info

check sqlserver uptime
SQLServer Uptime

If there is somebody that can share an image with a really old Sqlserver Uptime I will be glad to make a special post in this blog for it. Someone?

******Español

Hay un pequeño comando sql para saber el tiempo de actividad del SQLServer, abra el SSMS, abra una nueva ventana de consulta y pegue el comando de arriba, presione F5 y mire.

Si alguien puede compartir una foto que muestre el sql con más tiempo en actividad le haré un post especial en el blog. Quien se anima?